<?php
namespace App\Api\Controllers\DevicePay;


use App\Api\Controllers\Config\PayWaysController;
use App\Api\Controllers\Merchant\OrderController;
use App\Api\Controllers\Merchant\PayBaseController;
use App\Common\RefundSuccessAction;
use App\Exceptions\BizException;
use App\Models\Device;
use App\Models\Merchant;
use App\Models\MerchantStore;
use App\Models\MerchantWalletDetail;
use App\Models\MqttConfig;
use App\Models\Order;
use App\Models\RefundOrder;
use App\Models\RefundOrderDoing;
use App\Models\Store;
use App\Models\Glow;
use App\Api\Controllers\Config\VbillConfigController;
use App\Models\Stores;
use App\Models\UserWalletDetail;
use App\Services\Pay\PayService;
use App\Services\PrintSqlService;
use App\Services\Refund\RefundService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;

/**
 * 扫码设备支付接口
 * Class IndexController
 * @package App\Api\Controllers\DevicePay
 */
class IndexController extends BaseController
{

    //扫一扫收款
    public function scan_pay(Request $request)
    {

        try {
            $data = $request->getContent(); //获取请求参数
//             error_log(date('Y-m-d H:i:s')." 【基础被扫入参】： ".$data."\n\n", 3, "/www/wwwlogs/wft/pay-params.log");
            $data = json_decode($data, true);
            Log::channel('pay')->info(date('Y-m-d H:i:s')."-基础被扫入参scan_pay_store-".($data["store_id"]??"")."-金额-".$data["total_amount"],$data);
            if(isset($data['goods'])){
                $goods=$data['goods'];
                unset($data['goods']);
                $goods_detail=array();
                foreach($goods as $k=>$v){
                    $goods_detail[$k]['goods_name']=$v['goods_name'];
                    $goods_detail[$k]['quantity']=intval($v['count']);
                    $goods_detail[$k]['price']=bcmul((string)$v['goods_price'],"100");
                    $goods_detail[$k]['goods_id']=$v['goods_code'];
                }
                $Detail['receipt_id']=time();
                $Detail['goods_detail']=$goods_detail;
                $Detail['cost_price']=bcmul((string)$data['total_amount'],"100");
                $couponDetail = json_encode($Detail,JSON_UNESCAPED_UNICODE);
            }else{
                $couponDetail='';
            }
            //验证签名
            $check = $this->check_md5($data);
            if ($check['return_code'] == 'FALL') {
//                return $this->return_data($check);
            }

            $check_data = [
                'total_amount' => '付款金额',
                'code' => '付款码编号',
                'device_id' => '设备编号',
                'device_type' => '设备类型'
            ];
            $check = $this->check_required($data, $check_data);
            if ($check) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $check
                ];

                return $this->return_data($err);
            }
            if(isset($data['user_id'])){
                $store_user_id=DB::table('stores')->where('store_id',$data['store_id'])->first();
                $sub_users=$this->getSubIds($store_user_id->user_id);
                $sub_users[]=$data['user_id'];
                if(!in_array($data['user_id'],$sub_users)){
                    $err = [
                        'return_code' => 'FALL',
                        'return_msg' => '请联系服务商处理'
                    ];
                    return $this->return_data($err);
                }else{
                    unset($data['user_id']);
                }
            }

            $code = $data['code'];
            $total_amount = $data['total_amount'];
            $shop_price = isset($data['shop_price']) ? $data['shop_price'] : $data['total_amount'];
            $device_id = $data['device_id'];
            $device_type = $data['device_type'];
            $shop_name = isset($data['shop_name']) ? $data['shop_name'] : "扫一扫付款";
            $shop_desc = isset($data['shop_desc']) ? $data['shop_desc'] : "扫一扫付款";
            $other_no = isset($data['other_no']) ? $data['other_no'] : "";
            $remark = isset($data['remark']) ? $data['remark'] : "";
            $store_id = isset($data['store_id']) ? $data['store_id'] : "";
            $merchant_id = isset($data['merchant_id']) ? $data['merchant_id'] : "0";

            //有门店ID
            if ($store_id) {
                $merchant_name = '';
                $config_id = '';
            } else {
                //银豹
                if ($device_type == "pospal") {
                    $merchant_id = '0';
                    $merchant_name = '0';
                    $store_id = $device_id;
                    $config_id = '';
                } else {
                    $Device = Device::where('device_type', $device_type)
                        ->where('device_no', $device_id)
                        ->select('merchant_id', 'merchant_name', 'store_id', 'config_id')
                        ->first();
                    if (!$Device) {
                        $err = [
                            'return_code' => 'FALL',
                            'return_msg' => '设备未绑定'
                        ];
                        return $this->return_data($err);
                    }

                    $merchant_id = $Device->merchant_id;
                    $merchant_name = $Device->merchant_name;
                    $store_id = $Device->store_id;
                    $config_id = $Device->config_id;
                }
            }

            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
                'result_code' => '',
                'result_msg' => '',
                'other_no' => $other_no,
                'store_id' => $store_id,
                'ways_source' => '',
                'ways_source_desc' => '',
                'total_amount' => $total_amount
            ];

            //请求参数
            $data = [
                'config_id' => $config_id,
                'merchant_id' => $merchant_id,
                'merchant_name' => $merchant_name,
                'code' => $code,
                'total_amount' => $total_amount,
                'shop_price' => $shop_price,
                'remark' => $remark,
                'device_id' => $device_id,
                'shop_name' => $shop_name,
                'shop_desc' => $shop_desc,
                'store_id' => $store_id,
                'other_no' => $other_no,
                'couponDetail'=>$couponDetail
            ];

            $pay_obj = new PayBaseController();
            $scan_pay_public="";
            try {
                $scan_pay_public = $pay_obj->scan_pay_public($data);
            }catch (\Exception $e){
                Log::channel("vbill")->info("vbill-exception",[
                    "error"=>$e->getMessage().$e->getFile().$e->getLine()
                ]);
            }
            $tra_data_arr = json_decode($scan_pay_public, true);
            if ($tra_data_arr['status'] != 1) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $tra_data_arr['message'],
                    'result_code' => 'FALL',
                    'result_msg' => $tra_data_arr['message']
                ];
                return $this->return_data($err);
            }
            //用户支付成功
            if ($tra_data_arr['pay_status'] == '1') {
                //微信，支付宝支付凭证
                $re_data['result_code'] = 'SUCCESS';
                $re_data['result_msg'] = '支付成功';
                $re_data['out_trade_no'] = $tra_data_arr['data']['out_trade_no'];
                $re_data['trade_no'] = empty($tra_data_arr['data']['trade_no'])?'':$tra_data_arr['data']['trade_no'];
                $re_data['out_transaction_id'] = $tra_data_arr['data']['out_trade_no'];
                $re_data['pay_time'] = date('YmdHis', strtotime(isset($tra_data_arr['data']['pay_time']) ? $tra_data_arr['data']['pay_time'] : time()));
                $re_data['ways_source'] = $tra_data_arr['data']['ways_source'];

                $re_data['qwx_no'] = empty($tra_data_arr['data']['qwx_no'])?'':$tra_data_arr['data']['qwx_no'];

                // 诺诺开票
                $pay_obj = new PayBaseController();
                 $billing = $pay_obj->billing($tra_data_arr['data']['out_trade_no']); // 开票地址
                 $billing = json_decode($billing, true);
                 if($billing['code'] == 'E0000'){
                    $re_data['invoice_url'] = $billing['result']['ewmUrl'];
                 }



                if ($re_data['ways_source'] == 'alipay') {
                    $re_data['ways_source_desc'] = "支付宝";
                }

                if ($re_data['ways_source'] == 'weixin') {
                    $re_data['ways_source_desc'] = "微信支付";
                }

                if ($re_data['ways_source'] == 'jd') {
                    $re_data['ways_source_desc'] = "京东支付";
                }

                if ($re_data['ways_source'] == 'unionpay') {
                    $re_data['ways_source_desc'] = "银联";
                }
            } else if ($tra_data_arr['pay_status'] == '2') {
                //正在支付
                $re_data['result_code'] = 'USERPAYING';
                $re_data['result_msg'] = '用户正在支付';
                $re_data['out_trade_no'] = $tra_data_arr['data']['out_trade_no'];
                $re_data['ways_source'] = $tra_data_arr['data']['ways_source'];

                if ($re_data['ways_source'] == 'alipay') {
                    $re_data['ways_source_desc'] = "支付宝";
                }

                if ($re_data['ways_source'] == 'weixin') {
                    $re_data['ways_source_desc'] = "微信支付";
                }

                if ($re_data['ways_source'] == 'jd') {
                    $re_data['ways_source_desc'] = "京东支付";
                }

                if ($re_data['ways_source'] == 'unionpay') {
                    $re_data['ways_source_desc'] = "银联";
                }
            } else {
                //其他错误
                $re_data['result_code'] = 'FALL';
                $re_data['result_msg'] = $tra_data_arr['message'];
                $re_data['ways_source'] = $tra_data_arr['data']['ways_source'];

                if ($re_data['ways_source'] == 'alipay') {
                    $re_data['ways_source_desc'] = "支付宝";
                }

                if ($re_data['ways_source'] == 'weixin') {
                    $re_data['ways_source_desc'] = "微信支付";
                }

                if ($re_data['ways_source'] == 'jd') {
                    $re_data['ways_source_desc'] = "京东支付";
                }

                if ($re_data['ways_source'] == 'unionpay') {
                    $re_data['ways_source_desc'] = "银联";
                }
                //处理支付失败订单
                if ($tra_data_arr['pay_status'] == '3' || $tra_data_arr['pay_status'] == 3) {
                    if (!empty($tra_data_arr['data']['out_trade_no'])) {
                        $payservice=new PayService();
                        $payservice->closeOrder($tra_data_arr['data']['out_trade_no']);
                    }
                }
                //处理支付失败订单
            }
            return $this->return_data($re_data);
        } catch (\Exception $exception) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine()
            ];
            return $this->return_data($err);
        }
    }

    //萤火虫获取设备类型
    public function yhc_initdevicebrand(Request $request){
        $data = $request->getContent(); //获取请求参数
        $data = json_decode($data, true);
        $url='https://internal.congmingpay.com/internal/initdevicebrand.do';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1); // post数据
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        $output = curl_exec($ch);
        curl_close($ch);
        //返回数据
        return $output;
    }

    //萤火虫获取插件软件
    public function yhc_initgwwsoftmsg(Request $request){
        $data = $request->getContent(); //获取请求参数
        $url='https://internal.congmingpay.com/internal/initgwwsoftmsg.do?'.$data;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1); // post数据
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        $output = curl_exec($ch);
        curl_close($ch);
        //返回数据
        return $output;
    }

    //萤火虫获取插件软件
    public function yhc_inityhcv5softmsg(Request $request){
        $data = $request->getContent(); //获取请求参数
        $url='https://internal.congmingpay.com/internal/inityhcv5softmsg.do?'.$data;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1); // post数据
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        $output = curl_exec($ch);
        curl_close($ch);
        //返回数据
        return $output;
    }

    //萤火虫扫码下单接口
    public function yhc_pay(Request $request){
        $data = $request->getContent(); //获取请求参数
        $data = json_decode($data, true);
        // file_put_contents('congmingfu.log',var_export($data,true)."\r\n",FILE_APPEND);
        $check = $this->check_yhcmd5($data);
        if ($check['return_code'] == 'FALL') {
            return $this->return_data($check);
        }

        $check_data = [
            'money' => '付款金额',
            'auth_code' => '付款码编号',
            'shop_id' => '平台商户号',
            'order_id' => '平台订单号'
        ];
        $check = $this->check_required($data, $check_data);
        if ($check) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $check
            ];
            return $this->return_data($err);
        }
        $sn = Glow::where('device_id', $data['sn'])
                ->select('merchant_id','store_id')
                ->first();
        $code = $data['auth_code'];
        $total_amount = $data['money'];
        $shop_price = isset($data['shop_price']) ? $data['shop_price'] : $data['money'];
        $device_id = isset($data['sn']) ? $data['sn'] : 0;
        $device_type = isset($data['device_type']) ? $data['device_type'] : 0;
        $shop_name = isset($data['shop_name']) ? $data['shop_name'] : "扫一扫付款";
        $shop_desc = isset($data['shop_desc']) ? $data['shop_desc'] : "扫一扫付款";
        $other_no = isset($data['order_id']) ? $data['order_id'] : "";
        $remark = isset($data['remark']) ? $data['remark'] : "";
        $couponDetail = isset($data['detail']) ? $data['detail'] : "";
        $store_id = isset($sn->store_id) ? $sn->store_id : "";
        $merchant_id = isset($sn->merchant_id) ? $sn->merchant_id : "0";
        //有门店ID
        if ($store_id) {
            $merchant_name = '';
            $config_id = '';
        } else {
            //银豹
            if ($device_type == "pospal") {
                $merchant_id = '0';
                $merchant_name = '0';
                $store_id = $device_id;
                $config_id = '';
            } else {
                $Device = Device::where('device_type', $device_type)
                    ->where('device_no', $device_id)
                    ->select('merchant_id', 'merchant_name', 'store_id', 'config_id')
                    ->first();
                if (!$Device) {
                    $err = [
                        'return_code' => 'FALL',
                        'return_msg' => '设备未绑定'
                    ];
                    return $this->return_data($err);
                }


                $merchant_id = $Device->merchant_id;
                $merchant_name = $Device->merchant_name;
                $store_id = $Device->store_id;
                $config_id = $Device->config_id;
            }
        }

        //公共返回参数
        $re_data = [
            'result_code' => 'success',
            'order_id' => $other_no
        ];

        //请求参数
        $data = [
            'config_id' => $config_id,
            'merchant_id' => $merchant_id,
            'merchant_name' => $merchant_name,
            'code' => $code,
            'total_amount' => $total_amount,
            'shop_price' => $shop_price,
            'remark' => $remark,
            'device_id' => $device_id,
            'shop_name' => $shop_name,
            'shop_desc' => $shop_desc,
            'store_id' => $store_id,
            'other_no' => $other_no,
            'couponDetail'=>$couponDetail
        ];
        $pay_obj = new PayBaseController();
        $scan_pay_public = $pay_obj->scan_pay_public($data);
        $tra_data_arr = json_decode($scan_pay_public, true);
        if ($tra_data_arr['status'] != 1) {
            $err = [
                'pay_status' => 'fail',
                'error_msg' => $tra_data_arr['message'],
            ];
            return $this->return_yhcdata($err);
        }
        //用户支付成功
        if ($tra_data_arr['pay_status'] == '1') {
            //微信，支付宝支付凭证
            $re_data['pay_status'] = 'success';
            $re_data['transaction_id'] = $tra_data_arr['data']['trade_no'];
            $re_data['channel_trade_no'] = $tra_data_arr['data']['trade_no'];
            $re_data['pay_money'] = $tra_data_arr['data']['total_amount'];
            $re_data['pay_time'] = date('YmdHis', strtotime(isset($tra_data_arr['data']['pay_time']) ? $tra_data_arr['data']['pay_time'] : time()));
        }else if ($tra_data_arr['pay_status'] == '2') {
            //正在支付
            $re_data['pay_status'] = 'paying';
            $re_data['pay_money'] = $shop_price;
            $re_data['time_end'] = date('YmdHis', time());
        }else{
            $re_data['pay_status'] = 'fail';
            $re_data['pay_fail_msg'] = $tra_data_arr['message'];
        }
        return $this->return_yhcdata($re_data);
    }

    //萤火虫订单查询接口
    public function yhc_orderquery(Request $request){
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);
            //验证签名
            $check = $this->check_yhcmd5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }
            $order = Order::where('other_no', $data['order_id'])->first();
            $store = Store::where('shop_id', $data['shop_id'])->select('store_id')->first();
            $other_no = isset($data['order_id']) ? $data['order_id'] : '';
            $out_trade_no = isset($order->out_trade_no) ? $order->out_trade_no : "";
            $device_id = isset($data['device_id']) ? $data['device_id'] : 0;
            $device_type = isset($data['device_type']) ? $data['device_type'] : 0;

            $store_id = isset($order->store_id) ? $order->store_id : "";
            $merchant_id = isset($data['merchant_id']) ? $data['merchant_id'] : "";
            //有门店ID
            if ($store_id) {
                $merchant_name = '';
                $config_id = '';
            } else {
                //银豹
                if ($device_type == "pospal") {
                    $merchant_id = '0';
                    $merchant_name = '0';
                    $store_id = $device_id;
                    $config_id = '';
                } else {
                    $Device = Device::where('device_type', $device_type)
                        ->where('device_no', $device_id)
                        ->first();
                    if (!$Device) {
                        $err = [
                            'return_code' => 'FALL',
                            'return_msg' => '设备未绑定'
                        ];
                        return $this->return_data($err);
                    }

                    $merchant_id = $Device->merchant_id;
                    $merchant_name = $Device->merchant_name;
                    $store_id = $Device->store_id;
                    $store_name = $Device->store_name;
                    $config_id = $Device->config_id;
                }
            }

            //公共返回参数
            $re_data = [
                'result_code' => 'success',
                'order_id' => $data['order_id'],
            ];

            $data = [
                'out_trade_no' => $out_trade_no,
                'other_no' => $other_no,
                'store_id' => $store_id,
                'ways_type' => '',
                'config_id' => $config_id
            ];
            $order_obj = new OrderController();
            $return = $order_obj->order_foreach_public($data);
            $tra_data_arr = json_decode($return, true);
            if ($tra_data_arr['status'] != 1) {
                $err = [
                    'pay_status' => 'fail',
                    'pay_fail_msg' => '支付失败',
                ];
                return $this->return_yhcdata($err);
            }

            //用户支付成功
            if ($tra_data_arr['pay_status'] == '1') {
                 //微信，支付宝支付凭证
                $re_data['pay_status'] = 'success';
                $re_data['transaction_id'] = $tra_data_arr['data']['trade_no'];
                $re_data['channel_trade_no'] = $tra_data_arr['data']['trade_no'];
                $re_data['pay_money'] = $tra_data_arr['data']['total_amount'];
                $re_data['pay_time'] = date('YmdHis', strtotime(isset($tra_data_arr['data']['pay_time']) ? $tra_data_arr['data']['pay_time'] : time()));
            } elseif ($tra_data_arr['pay_status'] == '2') {
                //正在支付
                $re_data['order_id'] = $tra_data_arr['data']['out_trade_no'];
                $re_data['pay_status'] = 'paying';
                $re_data['pay_money'] = $order['total_amount'];
                $re_data['time_end'] = date('YmdHis', time());
            } else {
                //其他错误
                $re_data['order_id'] = $tra_data_arr['data']['out_trade_no'];
                $re_data['pay_status'] = 'fail';
                $re_data['pay_fail_msg'] = '支付失败';
            }
            return $this->return_yhcdata($re_data);
        } catch (\Exception $exception) {
            $err = [
                'return_code' => 'fail',
                'return_msg' => $exception->getMessage() . $exception->getLine()
            ];
            return $this->return_yhcdata($re_data);
        }
    }

    //萤火虫退款接口
    public function yhc_refund(Request $request){
        try {
            $data = $request->getContent();
            $data = json_decode($data, true);
            //验证签名
            $check = $this->check_yhcmd5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }
            $order=Order::where('other_no', $data['order_id'])->first()->toArray();
            $device_id = isset($order['device_id']) ? $order['device_id'] : "";
            $device_type = isset($order['device_type']) ? $order['device_type'] : "";
            $out_trade_no = isset($order['out_trade_no']) ? $order['out_trade_no'] : "";
            $refund_amount = isset($data['money']) ? $data['money'] : "";
            $refund_no = isset($order['refund_no'])?$order['refund_no'] : $out_trade_no . '123';

            $store_id = isset($order['store_id']) ? $order['store_id'] : "";
            $merchant_id = isset($order['merchant_id']) ? $order['merchant_id'] : "";

            //有门店ID
            if ($store_id) {
                $merchant_name = '';
                $config_id = '';
            } else {
                //银豹
                if ($device_type == "pospal") {
                    $merchant_id = '0';
                    $merchant_name = '0';
                    $store_id = $device_id;
                    $config_id = '';
                } else {
                    $Device = Device::where('device_type', $device_type)
                        ->where('device_no', $device_id)
                        ->first();
                    if (!$Device) {
                        $err = [
                            'return_code' => 'FALL',
                            'return_msg' => '设备未绑定'
                        ];
                        return $this->return_data($err);
                    }

                    $merchant_id = $Device->merchant_id;
                    $merchant_name = $Device->merchant_name;
                    $store_id = $Device->store_id;
                    $config_id = $Device->config_id;
                }
            }

             //公共返回参数
            $re_data = [
                'result_code' => 'success',
                'order_id' => $data['order_id'],

            ];

            //请求参数
            $data = [
                'merchant_id' => $merchant_id,
                'out_trade_no' => $out_trade_no,
                'refund_amount' => $refund_amount,
                'refund_no' => $refund_no
            ];
            $pay_obj = new OrderController();
            $scan_pay_public = $pay_obj->refund_public($data);
            $tra_data_arr = json_decode($scan_pay_public, true);

            if ($tra_data_arr['status'] != 1) {
                $err = [
                    'pay_status' => 'fail',
                    'error_msg' => $tra_data_arr['message'],
                ];
                return $this->return_data($err);
            }
            //退款成功
            if ($tra_data_arr['status'] == 1) {
                $re_data['refund_status'] = 'success';
                $re_data['refund_transaction_id'] = $tra_data_arr['data']['refund_no'];
            } elseif ($tra_data_arr['status'] == 2) {
                //正在支付
                $re_data['refund_status'] = 'success';
            } else {
                //其他错误
                $re_data['refund_status'] = 'fail';
            }
            return $this->return_yhcdata($re_data);
        } catch (\Exception $exception) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine()
            ];
            return $this->return_data($err);
        }
    }

    //萤火虫退款查询接口
    public function yhc_refundquery(Request $request){
        $data = $request->getContent();
        $data = json_decode($data, true);
    }

    //农行静态码回调
    public function abc_notifyurl(Request $request){
    }

    //获取店铺资料接口
    public function getStoreInfo(Request $request){
        $data = $request->getContent();
        $data = json_decode($data, true);
        $device_id=$data['device_id'];
        $device=Device::where('device_no', $device_id)->first();
        if(empty($device)){
            $err = [
                'return_code' => 'FALL',
                'return_msg' => '不存在该设备'
            ];
            return json_encode($err);
        }
        $store = DB::table("stores")->select("stores.store_id","stores.merchant_id","stores.store_name", "stores.store_short_name","stores.province_name","stores.city_name","stores.area_name","stores.store_address",
            "stores.people", "stores.people_phone","stores.s_time","stores.e_time", "stores.announcement", "stores.bg_image", "stores.logo","store_imgs.store_logo_img","store_imgs.store_license_img","store_imgs.store_logo_img_little", "store_imgs.store_img_a", "store_imgs.store_img_b", "store_imgs.store_img_c",
            "store_imgs.store_other_img","store_imgs.store_other_img_a","store_imgs.store_other_img_b","store_imgs.store_other_img_c","store_imgs.store_logo_img",
            "store_imgs.store_auth_bank_img", "store_imgs.store_qr_code")
            ->leftJoin("store_imgs","store_imgs.store_id","=","stores.store_id")
            ->where("stores.store_id","=",$device->store_id)
            ->first();
        $result=array(
            'store_id'=>$device->store_id,
            'merchant_id'=>$device->merchant_id,
            'device_id'=>$device->device_no,
            'device_type'=>$device->device_type,
            'StoreInfo'=>$store,
        );
        return json_encode($result);
    }

    //获取店铺资料接口
    public function getStoreHaiDian(Request $request){
        $data = $request->getContent();
        file_put_contents('b25235.log',var_export($data,true)."\r\n",FILE_APPEND);
        $data = json_decode($data, true);
        $store_id=$data['store_id'];
        $device=Device::where('store_id', $store_id)->where('device_type','x_haidian')->first();
        if(empty($device)){
            $err = [
                'status' => '2',
                'message' => '门店无海典设备'
            ];
            return json_encode($err);
        }
        $store = DB::table("stores")->select("stores.store_id","stores.merchant_id","stores.store_name", "stores.store_short_name","stores.province_name","stores.city_name","stores.area_name","stores.store_address",
            "stores.people", "stores.people_phone","stores.s_time","stores.e_time", "stores.announcement", "stores.bg_image", "stores.logo","store_imgs.store_logo_img","store_imgs.store_license_img","store_imgs.store_logo_img_little", "store_imgs.store_img_a", "store_imgs.store_img_b", "store_imgs.store_img_c",
            "store_imgs.store_other_img","store_imgs.store_other_img_a","store_imgs.store_other_img_b","store_imgs.store_other_img_c","store_imgs.store_logo_img",
            "store_imgs.store_auth_bank_img", "store_imgs.store_qr_code")
            ->leftJoin("store_imgs","store_imgs.store_id","=","stores.store_id")
            ->where("stores.store_id","=",$device->store_id)
            ->first();
        $result=array(
            'status'=>'1',
            'message'=>'获取成功',
            'store_id'=>$device->store_id,
            'merchant_id'=>$device->merchant_id,
            'device_id'=>$device->device_no,
            'device_type'=>$device->device_type,
            'StoreInfo'=>$store,
        );
        return json_encode($result);
    }

    //获取店铺资料接口
    public function getDeviceInfo(Request $request){

        $data = $request->getContent();
        $data = json_decode($data, true);
        $device_id=$data['device_id'];
        $device=Device::where('device_no', $device_id)->first();
        if(empty($device)){
            $result=array(
                'status'=>'2',
                'message'=>'系统内无此设备',
            );
            return json_encode($result);
        }
        $store = DB::table("stores")->select("stores.store_id","stores.merchant_id","stores.store_name", "stores.store_short_name","stores.province_name","stores.city_name","stores.area_name","stores.store_address",
            "stores.people", "stores.people_phone","stores.s_time","stores.e_time", "stores.announcement", "stores.bg_image", "stores.logo","store_imgs.store_logo_img","store_imgs.store_license_img","store_imgs.store_logo_img_little", "store_imgs.store_img_a", "store_imgs.store_img_b", "store_imgs.store_img_c",
            "store_imgs.store_other_img","store_imgs.store_other_img_a","store_imgs.store_other_img_b","store_imgs.store_other_img_c","store_imgs.store_logo_img",
            "store_imgs.store_auth_bank_img", "store_imgs.store_qr_code")
            ->leftJoin("store_imgs","store_imgs.store_id","=","stores.store_id")
            ->where("stores.store_id","=",$device['store_id'])
            ->first();
        if($device['type']=='x'&&$device['device_type']=='face_f4'){
            $result=array(
                'store_id'=>$device->store_id,
                'merchant_id'=>$device->merchant_id,
                'device_id'=>$device->device_no,
                'device_type'=>$device->device_type,
                'store_name'=>$store->store_name,
            );
        }else{
            $result=array(
                'store_id'=>$device->store_id,
                'merchant_id'=>$device->merchant_id,
                'device_id'=>$device->device_no,
                'device_type'=>$device->device_type,
                'store_name'=>$store->store_name,
                'status'=>'1',
                'message'=>'获取成功',
            );
        }
        return json_encode($result);
    }

    //公众号/小程序支付查询
    public function mini_order_query(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);

            // 验证签名
            // $check = $this->check_md5($data);
            // if ($check['return_code'] == 'FALL') {
            //     return $this->return_data($check);
            // }

            $other_no = isset($data['other_no']) ? $data['other_no'] : '';
            $out_trade_no = isset($data['out_trade_no']) ? $data['out_trade_no'] : "";
            $device_id = $data['device_id'];
            $device_type = $data['device_type'];

            $store_id = isset($data['store_id']) ? $data['store_id'] : "";
            $merchant_id = isset($data['merchant_id']) ? $data['merchant_id'] : "";
            //有门店ID
            if ($store_id) {
                $merchant_name = '';
                $config_id = '';
            } else {
                //银豹
                if ($device_type == "pospal") {
                    $merchant_id = '0';
                    $merchant_name = '0';
                    $store_id = $device_id;
                    $config_id = '';
                } else {
                    $Device = Device::where('device_type', $device_type)
                        ->where('device_no', $device_id)
                        ->first();
                    if (!$Device) {
                        $err = [
                            'return_code' => 'FALL',
                            'return_msg' => '设备未绑定'
                        ];
                        return $this->return_data($err);
                    }

                    $merchant_id = $Device->merchant_id;
                    $merchant_name = $Device->merchant_name;
                    $store_id = $Device->store_id;
                    $store_name = $Device->store_name;
                    $config_id = $Device->config_id;
                }
            }
            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
                'other_no' => $other_no,
                'store_id' => $store_id
            ];

            $data = [
                'out_trade_no' => $out_trade_no,
                'other_no' => $other_no,
                'store_id' => $store_id,
                'ways_type' => '',
                'config_id' => $config_id
            ];
            $order_obj = new OrderController();
            if($device_type=='x_biash'){
                $return = $order_obj->order_foreach_public($data);
            }else{
                $return = $order_obj->order_foreach_public_mini($data);
            }
            $tra_data_arr = json_decode($return, true);
            if ($tra_data_arr['status'] != 1) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $tra_data_arr['message']
                ];
                return $this->return_data($err);
            }

            //用户支付成功
            if ($tra_data_arr['pay_status'] == '1') {
                //微信，支付宝支付凭证
                $re_data['result_code'] = 'SUCCESS';
                $re_data['result_msg'] = '支付成功';
                $re_data['out_trade_no'] = $tra_data_arr['data']['out_trade_no'];
                // $re_data['out_transaction_id'] = $tra_data_arr['data']['trade_no'];
                $re_data['pay_time'] = date('YmdHis', strtotime($tra_data_arr['data']['pay_time']));
                $re_data['ways_source'] = $tra_data_arr['data']['ways_source'];;
                $re_data['pay_amount'] = isset($tra_data_arr['data']['pay_amount']) ? $tra_data_arr['data']['pay_amount'] : "";
                $re_data['total_amount'] = isset($tra_data_arr['data']['total_amount']) ? $tra_data_arr['data']['total_amount'] : "";
                $re_data['other_no'] = isset($tra_data_arr['data']['other_no']) ? $tra_data_arr['data']['other_no'] : "";
                // $re_data['tp_order_id'] = isset($tra_data_arr['data']['qwx_no']) ? $tra_data_arr['data']['qwx_no'] : "";
                $re_data['out_transaction_id'] = empty($tra_data_arr['data']['qwx_no'])?$tra_data_arr['data']['out_trade_no']:$tra_data_arr['data']['qwx_no'];
                $re_data['trade_no'] = $tra_data_arr['data']['trade_no'];

                //
                if ($re_data['ways_source'] == 'alipay') {
                    $re_data['ways_source_desc'] = "支付宝";
                }

                if ($re_data['ways_source'] == 'weixin') {
                    $re_data['ways_source_desc'] = "微信支付";
                }

                if ($re_data['ways_source'] == 'jd') {
                    $re_data['ways_source_desc'] = "京东支付";
                }

                if ($re_data['ways_source'] == 'unionpay') {
                    $re_data['ways_source_desc'] = "银联";
                }
            } elseif ($tra_data_arr['pay_status'] == '2') {
                //正在支付
                $re_data['result_code'] = 'USERPAYING';
                $re_data['result_msg'] = '用户正在支付';
                $re_data['out_trade_no'] = $tra_data_arr['data']['out_trade_no'];
            } else {
                //其他错误
                $re_data['result_code'] = 'FALL';
                $re_data['result_msg'] = $tra_data_arr['message'];
            }

            return $this->return_data($re_data);
        } catch (\Exception $exception) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine()
            ];
            return $this->return_data($err);
        }
    }

    //退款接口
    public function mini_refund(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);

            //验证签名
            // $check = $this->check_md5($data);
            // if ($check['return_code'] == 'FALL') {
            //     return $this->return_data($check);
            // }

            $device_id = isset($data['device_id']) ? $data['device_id'] : "";
            $device_type = isset($data['device_type']) ? $data['device_type'] : "";
            $out_trade_no = isset($data['out_trade_no']) ? $data['out_trade_no'] : "";
            $refund_amount = isset($data['refund_amount']) ? $data['refund_amount'] : "";
            $refund_no = isset($data['refund_no'])?$data['refund_no'] : $out_trade_no . '123';

            $store_id = isset($data['store_id']) ? $data['store_id'] : "";
            $merchant_id = isset($data['merchant_id']) ? $data['merchant_id'] : "";

            //有门店ID
            if ($store_id) {
                $merchant_name = '';
                $config_id = '';
            } else {
                //银豹
                if ($device_type == "pospal") {
                    $merchant_id = '0';
                    $merchant_name = '0';
                    $store_id = $device_id;
                    $config_id = '';
                } else {
                    $Device = Device::where('device_type', $device_type)
                        ->where('device_no', $device_id)
                        ->first();
                    if (!$Device) {
                        $err = [
                            'return_code' => 'FALL',
                            'return_msg' => '设备未绑定'
                        ];
                        return $this->return_data($err);
                    }

                    $merchant_id = $Device->merchant_id;
                    $merchant_name = $Device->merchant_name;
                    $store_id = $Device->store_id;
                    $config_id = $Device->config_id;
                }
            }

            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
                'result_code' => '',
                'result_msg' => '',
                'store_id' => $store_id,
                'out_trade_no' => $out_trade_no,
                'refund_amount' => $refund_amount
            ];

            //请求参数
            $data = [
                'merchant_id' => $merchant_id,
                'out_trade_no' => $out_trade_no,
                'refund_amount' => $refund_amount,
                'refund_no' => $refund_no
            ];
            $pay_obj = new OrderController();
            $scan_pay_public = $pay_obj->refund_public($data);
            $tra_data_arr = json_decode($scan_pay_public, true);
            if ($tra_data_arr['status'] != 1) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $tra_data_arr['message']
                ];
                return $this->return_data($err);
            }
            $re_data['other_no'] = $tra_data_arr['data']['other_no'];
            $re_data['refund_no'] = isset($tra_data_arr['data']['refund_no']) ? $tra_data_arr['data']['refund_no'] : $refund_no;
            $re_data['result_code'] = 'SUCCESS';
            $re_data['result_msg'] = '退款成功';

            $res_out_trade_no = isset($tra_data_arr['data']['out_trade_no']) ? $tra_data_arr['data']['out_trade_no'] : '';

            if ($res_out_trade_no) {
                $order_obj = Order::where('out_trade_no', $res_out_trade_no)->first();
                if ($order_obj) {
                    $re_data['ways_source'] = $order_obj->ways_source ? $order_obj->ways_source : '';

                    if ($re_data['ways_source'] == 'alipay') {
                        $re_data['ways_source_desc'] = "支付宝";
                    }

                    if ($re_data['ways_source'] == 'weixin') {
                        $re_data['ways_source_desc'] = "微信支付";
                    }

                    if ($re_data['ways_source'] == 'jd') {
                        $re_data['ways_source_desc'] = "京东支付";
                    }

                    if ($re_data['ways_source'] == 'unionpay') {
                        $re_data['ways_source_desc'] = "银联";
                    }
                }
            }
            return $this->return_data($re_data);
        } catch (\Exception $exception) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine()
            ];
            return $this->return_data($err);
        }
    }

    //退款查询接口
    public function mini_refund_query(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);

            //验证签名
            // $check = $this->check_md5($data);
            // if ($check['return_code'] == 'FALL') {
            //     return $this->return_data($check);
            // }

            $device_id = isset($data['device_id']) ? $data['device_id'] : "";
            $device_type = isset($data['device_type']) ? $data['device_type'] : "";
            $out_trade_no = isset($data['out_trade_no']) ? $data['out_trade_no'] : "";
            $store_id = isset($data['store_id']) ? $data['store_id'] : "";
            $refund_no = isset($data['refund_no']) ? $data['refund_no'] : "";

            $Order =DB::table('orders')->where('store_id', $store_id)->where('out_trade_no', $refund_no)->select('refund_amount','out_trade_no')->first();
            if(empty($Order)){
                $Order =DB::table('orders')->where('store_id', $store_id)->where('other_no', $refund_no)->select('refund_amount','out_trade_no')->first();
            }
            if(empty($Order->out_trade_no)){
                $RefundOrder = RefundOrder::where('store_id', $store_id)
                ->where('refund_no', $refund_no)
                ->select('refund_amount','out_trade_no')
                ->first();
            }else{
                $RefundOrder = RefundOrder::where('store_id', $store_id)
                ->where('out_trade_no', $Order->out_trade_no)
                ->select('refund_amount','out_trade_no')
                ->first();
            }
            if (!$RefundOrder) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => '退款单号不存在'
                ];
                return $this->return_data($err);
            }

            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
                'result_code' => '',
                'result_msg' => '',
                'store_id' => $store_id,
                'out_trade_no' => $RefundOrder->out_trade_no,
                'refund_amount' => $RefundOrder->refund_amount
            ];

            $re_data['result_code'] = 'SUCCESS';
            $re_data['result_msg'] = '退款成功';

            if ($RefundOrder->out_trade_no) {
                $order_obj = Order::where('out_trade_no', $RefundOrder->out_trade_no)->first();
                if ($order_obj) {
                    $re_data['ways_source'] = $order_obj->ways_source ? $order_obj->ways_source : '';

                    if ($re_data['ways_source'] == 'alipay') {
                        $re_data['ways_source_desc'] = "支付宝";
                    }

                    if ($re_data['ways_source'] == 'weixin') {
                        $re_data['ways_source_desc'] = "微信支付";
                    }

                    if ($re_data['ways_source'] == 'jd') {
                        $re_data['ways_source_desc'] = "京东支付";
                    }

                    if ($re_data['ways_source'] == 'unionpay') {
                        $re_data['ways_source_desc'] = "银联";
                    }
                }
            }

            return $this->return_data($re_data);
        } catch (\Exception $exception) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine()
            ];
            return $this->return_data($err);
        }
    }

    //付款码交换openid
    public function queryOpenid(Request $request)
    {
        try {
            $data = $request->getContent(); //获取请求参数
            $data = json_decode($data, true);

            // //验证签名
            // $check = $this->check_md5($data);
            // if ($check['return_code'] == 'FALL') {
            //     return $this->return_data($check);
            // }

            $check_data = [
                'code' => '付款码编号',
                'device_id' => '设备编号',
                'device_type' => '设备类型'
            ];
            $check = $this->check_required($data, $check_data);
            if ($check) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $check
                ];
                return $this->return_data($err);
            }

            $code = $data['code'];
            $device_id = $data['device_id'];
            $device_type = $data['device_type'];
            $store_id = isset($data['store_id']) ? $data['store_id'] : "";
            $merchant_id = isset($data['merchant_id']) ? $data['merchant_id'] : "0";

            //有门店ID
            if ($store_id) {
                $merchant_name = '';
                $config_id = '';
            } else {
                //银豹
                if ($device_type == "pospal") {
                    $merchant_id = '0';
                    $merchant_name = '0';
                    $store_id = $device_id;
                    $config_id = '';
                } else {
                    $Device = Device::where('device_type', $device_type)
                        ->where('device_no', $device_id)
                        ->select('merchant_id', 'merchant_name', 'store_id', 'config_id')
                        ->first();
                    if (!$Device) {
                        $err = [
                            'return_code' => 'FALL',
                            'return_msg' => '设备未绑定'
                        ];
                        return $this->return_data($err);
                    }

                    $merchant_id = $Device->merchant_id;
                    $merchant_name = $Device->merchant_name;
                    $store_id = $Device->store_id;
                    $config_id = $Device->config_id;
                }
            }



            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
                'store_id' => $store_id,
            ];
            $store_pid=0;
            $config = new VbillConfigController();
            $h_merchant = $config->vbill_merchant($store_id, $store_pid);
            if (!$h_merchant) {
                return json_encode([
                    'status' => 2,
                    'message' => '随行付商户号不存在'
                ]);
            }


            $obj = new \App\Api\Controllers\Vbill\PayController();
            $data1['request_url'] = 'https://openapi.tianquetech.com/query/getSubOPenid'; //请求地址
            $data1['mno'] = $h_merchant->mno;
            $data1['subMchId'] = $h_merchant->childNo; //
            $data1['subAppId'] = $h_merchant->wx_channel_appid; //
            $data1['authCode'] = $data['code']; //
            $data1['privateKey'] = 'MIIEowIBAAKCAQEArWjF7nnVl+4O0njSqnKuufO++eUvz1Hv/X1PcUJumHlmo3fcahMyf2EeMM9KKtvhVWKx9kZX+NeMAoTND2/lyMoPWkMLZaZ9LKrJNmQOO+e6oV11n1BtMtDRCIG3zk1bNhh8h8cm4RUZDazPDWwlfSqaG9z1G4w6Rdq0z0SaFTZYN7UXwBte2Oi3d1sc42D5IIf8xGS0uy/51LrcUh1ffFNrZ1QynEpTi/MfIALAEZ8t1DnLMTgG4KhulnP4on1s/jVA5O8lJNj7g0/0zqL7WJA6Hh7699CakHiAdq2JX1QEAbutVPBihbsS0N6nxJc/toI5X7L+HUd21wqZKgi3rQIDAQABAoIBAHOx/KTgOoa0OMVqATvhafv8yQUXSS+sPk9E5NTu+rTWAom79Z38Euvzkt4D3zr7GrsKLyvdwOHwhaREkD/la0zsqxOQubDnRIqho7+bP/ft4pG4tjpFwaVutphTW5vT9q//5E3+rEzt85oxGq+c4OJCozFF2W64v0RN5+aFobvWPW1vFulzTqRNV/WIwftdYkRR/aYSA7o9Mzk92BkeHNF3ct+8bcYj3aSYOsW6JdySqmMmo8sjsEFI1fyGqA4LHI3rUY0BpvV/3+uaiPWOHaMaMmeM4JSNDeRjuZv3Q0bNWSdJESAjqDCvTWWCDvUkWrREtDU8+hk7EMGESGhEaC0CgYEA4fNVLW2gq8paeS8EmjGJtQM2fftkDFyXHfuWcAnUPb6Qn51TQc+2fgm2gZbnudBFTroVRpy9fzRbgSQ7L1Noua8ximU/n2bxRFKkcZ3WtEwC1i1xmli6QhrWJuNAobtEgaHWQbyD+6kOGyLaLTR7Y2B1Y9EOsNdpOg1HDabxELMCgYEAxHihoJWA4yx2P7e7hplfI9VBmwc6pQHknenwcTrZBOQyKd/MmhAsRqrIJmoiX+S8tkchbUj+/e8M3O2AhYGrxgU0QIduKPFYndkM9L5Rseu5vkHjHh1S/5fYiq0C8xeo0Rmbus2uA6seMsdpsAEOq7hlcASnyJFA03mTnkR+hh8CgYAcDOFeKmXv7ccdlEC2A8BcwHFbYoIhJr1782fRsOawY6AAsL9NREQbkYkevWU3JCv2ghNyGLNNv2o8tgrC7U/q/VzhGYC0gUsieEAB+t5Us7sGa83Wo308B6jeWwgDDASNM1IuBwE7lNkzdTgwtHs88xSft6xjN9rQYiWYBEmZEQKBgF+J/aa2LLfLvjDb6q/YUyB8qmt1x3nIAuEbipW1NSUgxpgAQWFFrhIrKCst/0s8UtwcmM+o6H6ZSVsBjzbcyKgBjdg3Q0Vbn2kazCcTiWyIoYk4RvY08lBiCaXd3gpSHgCYgFcFf7I++u9cczNoQDcW8xTW3rQ0lh6AB122FwSnAoGBAN+0BVD2QfE39nj6MlUhsBFyHYqvF80466WgZ9tqIpFg32OzJwpnVN7LZpBv37J3Wp69c0lwCKwp7VtYog5d9kh+a0JJaWCk7dpH6DKVpyol9Y96USYHUUl+47H0BCfi13gL2YakQC1Wtmq5TB+TlERUrjnnWfiuJlTUr2YKXnY0'; //
             $data1['sxfpublic'] = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlfvtmSPySliKpkb3b77XmonlqCqO/DSLDhqoJnGZBMwHYxMHVdFE9uJEswA5/8F58ZV1o4GfudGuMMVOroYLTkofegXrI8WzONEHB1QJOxiNHwXGX1SL+3FykVk0FZITsp4yV3+j7cnSX5Y+y0QPqSCKZJi0XhlxF0wNihWNJ1JItq5xCuyGda2Kas5fn2Cd3rspbztYhGfGq+3I5AngNeHV2hhh1BGeQY++7F3H+cMGWL4DqFsV4+mFOTGNaBWde3PARlCDgSHSXkXcf6tLnKKqfby0YtnZpk0GTt5OO/7X/DZ7rFNJgPhEtMJeZcH+43DQtHSMF4P179OmAlulUwIDAQAB'; //
            $scan_pay_public = $obj->getSubOPenid($data1);

            //获取成功
            if ($scan_pay_public['status'] == '1') {
                $re_data['result_code'] = 'SUCCESS';
                $re_data['result_msg'] = '获取成功';
                $re_data['openId'] = $scan_pay_public['data']['respData']['openid'];
            }else {
                //其他错误
                $re_data['result_code'] = 'FALL';
                $re_data['result_msg'] = '获取失败';
            }

            return $this->return_data($re_data);
        } catch (\Exception $exception) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine()
            ];
            return $this->return_data($err);
        }
    }


    //动态二维码收款
    public function qr_pay(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);

            //验证签名
            $check = $this->check_md5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }


            $total_amount = $data['total_amount'];
            $shop_price = isset($data['shop_price']) ? $data['shop_price'] : $data['total_amount'];
            $device_id = $data['device_id'];
            $device_type = $data['device_type'];
            $ways_source = $data['ways_source'];
            if (empty($ways_source)){
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => "ways_source-必须传递"
                ];
                return $this->return_data($err);
            }
            $ways_type = $data['ways_type']??"";
            $notify_url = isset($data['notify_url']) ? $data['notify_url'] : "";
            $shop_name = isset($data['shop_name']) ? $data['shop_name'] : "扫一扫付款";
            $shop_desc = isset($data['shop_desc']) ? $data['shop_desc'] : "扫一扫付款";
            $other_no = isset($data['other_no']) ? $data['other_no'] : "";
            $remark = isset($data['remark']) ? $data['remark'] : "";

            $check_data = [
                'total_amount' => '付款金额',
                'ways_type' => '支付方式',
                'device_id' => '设备编号',
                'device_type' => '设备类型'
            ];
            $check = $this->check_required($data, $check_data);
            if ($check) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $check
                ];
                return $this->return_data($err);
            }

            $store_id = isset($data['store_id']) ? $data['store_id'] : "";
            $merchant_id = isset($data['merchant_id']) ? $data['merchant_id'] : "";

            //有门店ID
            if ($store_id) {
                $merchant_name = '';
                $config_id = '';
            } else {
                $Device = Device::where('device_type', $device_type)
                    ->where('device_no', $device_id)
                    ->first();
                if (!$Device) {
                    $err = [
                        'return_code' => 'FALL',
                        'return_msg' => '设备未绑定'
                    ];
                    return $this->return_data($err);
                }

                $merchant_id = $Device->merchant_id;
                $merchant_name = $Device->merchant_name;
                $store_id = $Device->store_id;
                $config_id = $Device->config_id;
            }

            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
                'other_no' => $other_no,
                'store_id' => $store_id,
                'ways_source' => $ways_source,
                'ways_source_desc' => ''
            ];

            $storeResult=Stores::query()->where(["store_id"=>$store_id])->first();
            if(empty($storeResult)){
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => "店铺不存在"
                ];
                return $this->return_data($err);
            }


            if (empty($ways_type)){
                $obj=new PayWaysController();
                if(empty($storeResult->pid)){
                    $store_p_id=(string)$store_id;
                }else{
                    $storeP=Stores::query()->where("id",$storeResult->pid)->first();
                    $store_p_id=(string)$storeP->store_id;
                }
                $ways=$obj->ways_source($ways_source,$store_id,$store_p_id);
                Log::info("qr_pay-ways_type-select",[
                    "ways"=>$ways,
                    "req"=>[$ways_source,$store_id,$store_p_id]
                ]);
                //验证扣费模式
                list($isRun,$error)=\App\Services\Store\StoreSignService::validateSign((string)$ways->store_id,(string)$ways->company);
                if($isRun==false){
                    $err = [
                        'return_code' => 'FALL',
                        'return_msg' => $error
                    ];
                    return $this->return_data($err);
                }
                $ways_type=$ways->ways_type;
            }
            if(empty($ways_type)){
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => "ways_type不存在"
                ];
                return $this->return_data($err);
            }
            //请求参数
            $data = [
                'config_id' => $config_id,
                'merchant_id' => $merchant_id,
                'merchant_name' => $merchant_name,
                'total_amount' => $total_amount,
                'shop_price' => $shop_price,
                'remark' => $remark,
                'device_id' => $device_id,
                'shop_name' => $shop_name,
                'shop_desc' => $shop_desc,
                'store_id' => $store_id,
                'other_no' => $other_no,
                'ways_source' => $ways_source,
                'notify_url' => $notify_url,
                'ways_type' => $ways_type
            ];

            $pay_obj = new PayBaseController();
            $scan_pay_public = $pay_obj->qr_pay_public($data);
            $tra_data_arr = json_decode($scan_pay_public, true);
            if ($tra_data_arr['status'] != 1) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $tra_data_arr['message']
                ];
                return $this->return_data($err);
            }

            //返回数据成功
            $re_data['out_trade_no'] = $tra_data_arr['data']['out_trade_no'];
            $re_data['code_url'] = $tra_data_arr['data']['code_url'];
            $re_data['store_name'] = $tra_data_arr['data']['store_name'];

            if ($re_data['ways_source'] == 'alipay') {
                $re_data['ways_source_desc'] = "支付宝";
            }

            if ($re_data['ways_source'] == 'weixin') {
                $re_data['ways_source_desc'] = "微信支付";
            }

            if ($re_data['ways_source'] == 'jd') {
                $re_data['ways_source_desc'] = "京东支付";
            }

            if ($re_data['ways_source'] == 'unionpay') {
                $re_data['ways_source_desc'] = "银联";
            }

            return $this->return_data($re_data);
        } catch (\Exception $exception) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine()
            ];
            return $this->return_data($err);
        }
    }


    //静态二维码
    public function qr_auth_pay(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);

            //验证签名
            $check = $this->check_md5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }

            $device_id = $data['device_id'];
            $device_type = $data['device_type'];
            $other_no = isset($data['other_no']) ? $data['other_no'] : "";
            $notify_url = isset($data['notify_url']) ? $data['notify_url'] : '';

            $check_data = [
                'device_id' => '设备编号',
                'device_type' => '设备类型'
            ];
            $check = $this->check_required($data, $check_data);
            if ($check) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $check,
                ];
                return $this->return_data($err);
            }

            $store_id = isset($data['store_id']) ? $data['store_id'] : "";
            $merchant_id = isset($data['merchant_id']) ? $data['merchant_id'] : "";

            //有门店ID
            if ($store_id) {
                $merchant_name = '';
                $config_id = '';
                $store_name = '';
                $Store = Store::where('store_id', $store_id)
                    ->select('store_short_name')
                    ->first();
                if ($Store) {
                    $store_name = $Store->store_short_name;
                }
            } else {
                $Device = Device::where('device_type', $device_type)
                    ->where('device_no', $device_id)
                    ->first();
                if (!$Device) {
                    $err = [
                        'return_code' => 'FALL',
                        'return_msg' => '设备未绑定'
                    ];
                    return $this->return_data($err);
                }

                $merchant_id = $Device->merchant_id;
                $merchant_name = $Device->merchant_name;
                $store_id = $Device->store_id;
                $store_name = $Device->store_name;
            }

            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
                'other_no' => $other_no,
                'store_id' => $store_id
            ];

            $server = $request->server();
            $server['SERVER_NAME'];
            $code_url = 'https://' . $server['SERVER_NAME'] . '/qr?store_id=' . $store_id . '&merchant_id=' . $merchant_id . '';

            //返回数据成功
            $re_data['out_trade_no'] = '';
            $re_data['code_url'] = $code_url;
            $re_data['store_name'] = $store_name;

            return $this->return_data($re_data);
        } catch (\Exception $exception) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine()
            ];
            return $this->return_data($err);
        }
    }


    //店铺通道开通类型
    public function store_pay_ways(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);

            //验证签名
            $check = $this->check_md5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }

            $device_id = $data['device_id'];
            $device_type = $data['device_type'];
            $scan_amount = "";

            $check_data = [
                'device_id' => '设备编号',
                'device_type' => '设备类型'
            ];
            $check = $this->check_required($data, $check_data);
            if ($check) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $check
                ];
                return $this->return_data($err);
            }

            $Device = Device::where('device_type', $device_type)
                ->where('device_no', $device_id)
                ->first();
            if (!$Device) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => '设备未绑定'
                ];
                return $this->return_data($err);
            }

            $store_id = $Device->store_id;
            $merchant_id = $Device->merchant_id;
            $store_name = $Device->store_name;
            $config_id = $Device->config_id;

            //
            $MqttConfig = MqttConfig::where('config_id', $config_id)->first();
            if (!$MqttConfig) {
                $MqttConfig = MqttConfig::where('config_id', '1234')->first();
            }
            if (!$MqttConfig) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => '未配置消息推送'
                ];
                return $this->return_data($err);
            }

            $mq_server = $MqttConfig->server;
            $mq_topic = $MqttConfig->topic;
            $mq_port = $MqttConfig->port;
            $mq_group_id = $MqttConfig->group_id;
            $mq_user_name = "Signature|" . $MqttConfig->access_key_id . "|" . $MqttConfig->instance_id . "";

            $str = '' . $MqttConfig->group_id . '@@@' . $device_id . '';
            $key = $MqttConfig->access_key_secret;
            $str = mb_convert_encoding($str, "UTF-8");
            $mq_user_password = base64_encode(hash_hmac("sha1", $str, $key, true));

            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
                'store_id' => $store_id,
                'config_id' => $config_id,
                'merchant_id' => $merchant_id,
                'store_name' => $store_name,
                'scan_amount' => $scan_amount,
                'mq_server' => $mq_server,
                'mq_topic' => $mq_topic,
                'mq_port' => $mq_port,
                'mq_group_id' => $mq_group_id,
                'client_id' => $mq_group_id . '@@@' . $device_id,
                'mq_user_name' => $mq_user_name,
                'mq_user_password' => $mq_user_password
            ];

            $data = DB::table('store_ways_desc')
                ->join('store_pay_ways', 'store_pay_ways.ways_type', '=', 'store_ways_desc.ways_type')
                ->where('store_pay_ways.store_id', $store_id)
                ->where('store_pay_ways.status', 1)
                ->where('store_pay_ways.is_close', 0)
                ->select('store_pay_ways.ways_type', 'store_pay_ways.ways_desc', 'store_pay_ways.ways_source', 'store_pay_ways.sort', 'store_pay_ways.rate')
                ->orderBy('store_pay_ways.sort', 'asc')
                ->get();

            //如果为空 看下是否为分店
            if ($data->isEmpty()) {
                $store = Store::where('store_id', $store_id)
                    ->select('pid')
                    ->first();
                //查总店
                if ($store && $store->pid) {
                    $store = Store::where('id', $store->pid)
                        ->select('store_id')
                        ->first();
                    if ($store) {
                        $data = DB::table('store_ways_desc')
                            ->join('store_pay_ways', 'store_pay_ways.ways_type', '=', 'store_ways_desc.ways_type')
                            ->where('store_pay_ways.store_id', $store->store_id)
                            ->where('store_pay_ways.status', 1)
                            ->where('store_pay_ways.is_close', 0)
                            ->select('store_pay_ways.ways_type', 'store_pay_ways.ways_desc', 'store_pay_ways.ways_source', 'store_pay_ways.sort', 'store_pay_ways.rate')
                            ->orderBy('store_pay_ways.sort', 'asc')
                            ->get();
                    }
                }
            }

            //返回数据成功
            $re_data['data'] = $data;

            return $this->return_data($re_data);
        } catch (\Exception $exception) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine()
            ];
            return $this->return_data($err);
        }
    }


    //小程序收款
    public function mini_pay(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            file_put_contents('b23432584.log',var_export($data,true)."\r\n",FILE_APPEND);
            $data = json_decode($data, true);

            //验证签名
            $check = $this->check_md5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }

            $merchant_id = $request->get('merchant_id');
            $merchant = Merchant::where('id', $merchant_id)
                ->select('name')
                ->first();
            $merchant_name = '';
            if ($merchant) {
                $merchant_name = $merchant->name;
            }

            $store_id = $data['store_id'];
            $store = Store::where('store_id', $store_id)
                ->select(['status','config_id', 'store_name', 'pid', 'user_id', 'is_delete', 'is_admin_close', 'is_close'])
                ->first();
            if (!$store) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => '没有关联认证门店请联系服务商',
                    'result_code' => 'FALL',
                    'result_msg' => '没有关联认证门店请联系服务商',
                ];

                return $this->return_data($err);
            }
            //关闭的商户禁止交易
            if ($store->is_close || $store->is_admin_close || $store->is_delete) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => '商户已经被服务商关闭',
                    'result_code' => 'FALL',
                    'result_msg' => '商户已经被服务商关闭',
                ];

                return $this->return_data($err);
            }

            if ($store->status!=1) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => '商户已经被服务商关闭',
                    'result_code' => 'FALL',
                    'result_msg' => '商户已经被服务商关闭',
                ];

                return $this->return_data($err);
            }

            $config_id = $store->config_id;
            $store_name = $store->store_name;
            $store_pid = $store->pid;
            $tg_user_id = $store->user_id;
            $total_amount = isset($data['total_amount']) ? $data['total_amount'] : "";
            $shop_price = isset($data['total_amount']) ? $data['total_amount'] : "";
            $remark = '';
            $device_id = isset($data['device_id']) ? $data['device_id'] : "";
            $device_type = isset($data['device_type']) ? $data['device_type'] : "";
            $shop_name = '收款';
            $shop_desc = '收款';;
            $open_id = isset($data['open_id']) ? $data['open_id'] : "";
            $ways_source = isset($data['ways_source']) ? $data['ways_source'] : "";
            $other_no = isset($data['other_no']) ? $data['other_no'] : "";
            $notify_url = isset($data['notify_url']) ? $data['notify_url'] : "";
            $pay_type = isset($data['pay_type']) ? $data['pay_type'] : "01";
            $pay_method = isset($data['pay_method']) ? $data['pay_method'] : "";

            $check_data = [
                'total_amount' => '付款金额'
            ];
            $check = $this->check_required($data, $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }

            if ($other_no == "" || $other_no == "NULL") {
                $other_no = "";
            }

            if ($notify_url == "" || $notify_url == "NULL") {
                $notify_url = "";
            }

            $obj_ways = new PayWaysController(['total_amount' => $total_amount]);
            if($pay_type=='01'){
                $ways = $obj_ways->ways_source($ways_source, $store_id, $store_pid);
            }else{
                if ($store_id == '20231120113031458031' || $store_id == '202442895849811363') {
                    $ways = DB::table('store_pay_ways')->where('ways_source', $ways_source)
                        ->where('company', 'weixin')
                        ->where('store_id', $store_id)
                        ->where('status', 1)
                        ->orderBy('sort', 'asc')
                        ->first();
                } else {
                    $ways = DB::table('store_pay_ways')->where('ways_source', $ways_source)
                        ->where('company', 'vbill')
                        ->where('store_id', $store_id)
                        ->where('status', 1)
                        ->orderBy('sort', 'asc')
                        ->first();
                }
            }
            if (!$ways) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => '没有开通此类型通道',
                    'result_code' => 'FALL',
                    'result_msg' => '没有开通此类型通道'
                ];
                return $this->return_data($err);
            }
            //验证扣费模式
            list($isRun,$error)=\App\Services\Store\StoreSignService::validateSign((string)$ways->store_id,(string)$ways->company);
            if($isRun==false){
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $error,
                    'result_code' => 'FALL',
                    'result_msg' => $error
                ];
                return $this->return_data($err);
            }
            $ways_type = $ways->ways_type;

            $data = [
                'merchant_name' => $merchant_name,
                'store_id' => $store_id,
                'merchant_id' => $merchant_id,
                'config_id' => $config_id,
                'store_name' => $store_name,
                'store_pid' => $store_pid,
                'tg_user_id' => $tg_user_id,
                'total_amount' => $total_amount,
                'shop_price' => $shop_price,
                'remark' => $remark,
                'device_id' => $device_id,
                'shop_name' => $shop_name,
                'shop_desc' => $shop_desc,
                'open_id' => $open_id,
                'ways_type' => $ways_type,
                'other_no' => $other_no,
                'notify_url' => $notify_url
            ];
            if(!empty($pay_method)){
                $data['pay_method']=$pay_method;
            }
            $pay_obj = new PayBaseController();
            if ($pay_type == "01") {
                if($device_type!='c_xjl_1'){
                    $scan_pay_public = $pay_obj->qr_auth_pay_public($data, $ways);
                }else{
                    $scan_pay_public = $pay_obj->qr_auth_pay_public1($data, $ways);
                }
            } else {
                $scan_pay_public = $pay_obj->mini_app_pay_public($data, $ways);
            }
            $tra_data_arr = json_decode($scan_pay_public, true);
            // file_put_contents('b.log',var_export($tra_data_arr,true)."\r\n",FILE_APPEND);
            if ($tra_data_arr['status'] != 1) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $tra_data_arr['message'],
                    'result_code' => 'FALL',
                    'result_msg' => $tra_data_arr['message']
                ];
                return $this->return_data($err);
            }

            $re_data = [];
            //支付宝
            if ($ways_source == "alipay") {
                //随行付
                if ($ways->company == "vbill") {
                    $re_data = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => '数据返回成功',
                        'result_code' => 'SUCCESS',
                        'result_msg' => '数据返回成功',
                        'trade_no' => $tra_data_arr['trade_no']
                    ];
                }

                //官方支付宝
                if ($ways->company == "alipay") {
                    $re_data = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => '数据返回成功',
                        'result_code' => 'SUCCESS',
                        'result_msg' => '数据返回成功',
                        'trade_no' => $tra_data_arr['trade_no']
                    ];
                }

               //新大陆
                if ($ways->company == "newland") {
                    $re_data = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => '数据返回成功',
                        'result_code' => 'SUCCESS',
                        'result_msg' => '数据返回成功',
                        'trade_no' => $tra_data_arr['trade_no']
                    ];
                }

                //快钱
                if ($ways->company == "mybank") {
                    $re_data = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => '数据返回成功',
                        'result_code' => 'SUCCESS',
                        'result_msg' => '数据返回成功',
                        'trade_no' => $tra_data_arr['trade_no']
                    ];
                }

                //dlb
                if ($ways->company == "dlb") {
                    $re_data = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => '数据返回成功',
                        'result_code' => 'SUCCESS',
                        'result_msg' => '数据返回成功',
                        'trade_no' => $tra_data_arr['reserved_transaction_id']
                    ];
                }

                //dlb
                if ($ways->company == "lianfu") {
                    $re_data = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => '数据返回成功',
                        'result_code' => 'SUCCESS',
                        'result_msg' => '数据返回成功',
                        'trade_no' => $tra_data_arr['data']
                    ];
                }
            }

            if ($ways_source == "weixin") {
                //随行付
                if ($ways->company == "vbill") {
                    $re_data = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => '数据返回成功',
                        'result_code' => 'SUCCESS',
                        'result_msg' => '数据返回成功',
                        'payTimeStamp' => $tra_data_arr['data']['payTimeStamp'],
                        'payPackage' => $tra_data_arr['data']['payPackage'],
                        'paySign' => $tra_data_arr['data']['paySign'],
                        'payAppId' => $tra_data_arr['data']['payAppId'],
                        'paynonceStr' => $tra_data_arr['data']['paynonceStr'],
                        'paySignType' => $tra_data_arr['data']['paySignType']
                    ];
                }

                //微信官方
                if ($ways->company == "weixin") {
                    //$tra_data_arr['data'] = json_decode($tra_data_arr['data'], true);
                    $re_data = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => '数据返回成功',
                        'result_code' => 'SUCCESS',
                        'result_msg' => '数据返回成功',
                        'payTimeStamp' => $tra_data_arr['data']['timeStamp'],
                        'payPackage' => $tra_data_arr['data']['package'],
                        'paySign' => $tra_data_arr['data']['paySign'],
                        'payAppId' => $tra_data_arr['data']['appId'],
                        'paynonceStr' => $tra_data_arr['data']['nonceStr'],
                        'paySignType' => $tra_data_arr['data']['signType']
                    ];
                }

                //快钱
                if ($ways->company == "mybank") {
                    $tra_data_arr['data'] = json_decode($tra_data_arr['data'], true);
                    $re_data = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => '数据返回成功',
                        'result_code' => 'SUCCESS',
                        'result_msg' => '数据返回成功',
                        'payTimeStamp' => $tra_data_arr['data']['timeStamp'],
                        'payPackage' => $tra_data_arr['data']['package'],
                        'paySign' => $tra_data_arr['data']['paySign'],
                        'payAppId' => $tra_data_arr['data']['appId'],
                        'paynonceStr' => $tra_data_arr['data']['nonceStr'],
                        'paySignType' => $tra_data_arr['data']['signType']
                    ];
                }

                //新大陆
                if ($ways->company == "newland") {
                    $tra_data_arr['data'] = json_decode($tra_data_arr['data'], true);
                    $re_data = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => '数据返回成功',
                        'result_code' => 'SUCCESS',
                        'result_msg' => '数据返回成功',
                        'payTimeStamp' => $tra_data_arr['data']['apiTimestamp'],
                        'payPackage' => $tra_data_arr['data']['apiPackage'],
                        'paySign' => $tra_data_arr['data']['apiPaysign'],
                        'payAppId' => $tra_data_arr['data']['apiAppid'],
                        'paynonceStr' => $tra_data_arr['data']['apiNoncestr'],
                        'paySignType' => $tra_data_arr['data']['apiSigntype']
                    ];
                }

                //多啦宝
                if ($ways->company == "dlb") {
                    $tra_data_arr['data'] = json_decode($tra_data_arr['data'], true);
                    $re_data = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => '数据返回成功',
                        'result_code' => 'SUCCESS',
                        'result_msg' => '数据返回成功',
                        'payTimeStamp' => $tra_data_arr['data']['TIMESTAMP'],
                        'payPackage' => $tra_data_arr['data']['PACKAGE'],
                        'paySign' => $tra_data_arr['data']['PAYSIGN'],
                        'payAppId' => $tra_data_arr['data']['APPID'],
                        'paynonceStr' => $tra_data_arr['data']['NONCESTR'],
                        'paySignType' => $tra_data_arr['data']['SIBGTYPE']
                    ];
                }

                if ($ways->company == "lianfu") {
                    $re_data = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => '数据返回成功',
                        'result_code' => 'SUCCESS',
                        'result_msg' => '数据返回成功',
                        'payPackage' => $tra_data_arr['data']['package'],
                        'paySign' => $tra_data_arr['data']['sign'],
                        'payAppId' => $tra_data_arr['data']['appid'],
                        'paynonceStr' => $tra_data_arr['data']['noncestr'],
                        'paySignType' => $tra_data_arr['data']['signType'],
                        'payTimeStamp' => $tra_data_arr['data']['timestamp'],
                    ];
                }

            }

            return $this->return_data($re_data);
        } catch (\Exception $exception) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine()
            ];
            return $this->return_data($err);
        }
    }


    //查询订单号状态
    public function order_query(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);
            //验证签名
            $check = $this->check_md5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }

            Log::channel("order_query")->info("order_query",[
              "req"=>$data
            ]);

            $other_no = isset($data['other_no']) ? $data['other_no'] : '';
            $out_trade_no = isset($data['out_trade_no']) ? $data['out_trade_no'] : "";
            $device_id = $data['device_id'];
            $device_type = $data['device_type'];

            $store_id = isset($data['store_id']) ? $data['store_id'] : "";
            $merchant_id = isset($data['merchant_id']) ? $data['merchant_id'] : "";

            //有门店ID
            if ($store_id) {
                $merchant_name = '';
                $config_id = '';
            } else {
                //银豹
                if ($device_type == "pospal") {
                    $merchant_id = '0';
                    $merchant_name = '0';
                    $store_id = $device_id;
                    $config_id = '';
                } else {
                    $Device = Device::where('device_type', $device_type)
                        ->where('device_no', $device_id)
                        ->first();
                    if (!$Device) {
                        $err = [
                            'return_code' => 'FALL',
                            'return_msg' => '设备未绑定'
                        ];
                        return $this->return_data($err);
                    }

                    $merchant_id = $Device->merchant_id;
                    $merchant_name = $Device->merchant_name;
                    $store_id = $Device->store_id;
                    $store_name = $Device->store_name;
                    $config_id = $Device->config_id;
                }
            }

            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
                'other_no' => $other_no,
                'store_id' => $store_id
            ];

            $channelCode = '';
            if (isset($data['channel_code']) && !empty($data['channel_code'])) {
                $channelCode = $data['channel_code'];
            }
            $sxfUuid = '';
            if (isset($data['sxf_uuid']) && !empty($data['sxf_uuid'])) {
                $sxfUuid = $data['sxf_uuid'];
            }
            $data = [
                'out_trade_no' => $out_trade_no,
                'other_no' => $other_no,
                'store_id' => $store_id,
                'ways_type' => '',
                'config_id' => $config_id,
                'channel_code' => $channelCode,
                'sxf_uuid' => $sxfUuid
            ];

            $order_obj = new OrderController();
            $return = $order_obj->order_foreach_public($data);
            $tra_data_arr = json_decode($return, true);
            if ($tra_data_arr['status'] != 1) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $tra_data_arr['message']
                ];
                return $this->return_data($err);
            }
            if(empty($re_data['ways_source'])){
                $re_data['ways_source'] = $tra_data_arr['data']['ways_source']??"";
            }
            //用户支付成功
            if ($tra_data_arr['pay_status'] == '1') {
                //微信，支付宝支付凭证
                $re_data['result_code'] = 'SUCCESS';
                $re_data['result_msg'] = '支付成功';
                $re_data['out_trade_no'] = $tra_data_arr['data']['out_trade_no'];
                $re_data['out_transaction_id'] = $tra_data_arr['data']['out_trade_no'];
                $re_data['pay_time'] = date('YmdHis', strtotime($tra_data_arr['data']['pay_time']));
                $re_data['ways_source'] = $tra_data_arr['data']['ways_source']??"";
                $re_data['pay_amount'] = isset($tra_data_arr['data']['pay_amount']) ? $tra_data_arr['data']['pay_amount'] : "";
                $re_data['total_amount'] = isset($tra_data_arr['data']['total_amount']) ? $tra_data_arr['data']['total_amount'] : "";
                $re_data['other_no'] = isset($tra_data_arr['data']['other_no']) ? $tra_data_arr['data']['other_no'] : "";
                $re_data['trade_no'] = $tra_data_arr['data']['trade_no']??"";

                $re_data['qwx_no'] = isset($tra_data_arr['data']['qwx_no']) ? $tra_data_arr['data']['qwx_no'] : "";

                // $re_data['invoice_url'] ='http://nnfpbox.nuonuocs.cn/invoice/scan/k.do?jc=NzA1NDA4ODA1NDA4MXJ6enJqcw==&on=MjExOTEyMDA4NzEwMjExNjA1MDA0ODA1MDA1MDA0ODA1NzA1MTA0ODA0OTA1MzA1MTA1MzA0OTA1NzA1NTA0ODA1NjA1MTA1MDA0ODA1NG5sbG5sbg==&flag=MDA5OTEwODEwNTEwMWJibGJiaw==';



                // 诺诺开票
                $pay_obj = new PayBaseController();
                $billing = $pay_obj->billing($tra_data_arr['data']['out_trade_no']); // 开票地址
                $billing = json_decode($billing, true);
                if($billing['code'] == 'E0000'){
                    $re_data['invoice_url'] = $billing['result']['ewmUrl'];
                }



                //
                if ($re_data['ways_source'] == 'alipay') {
                    $re_data['ways_source_desc'] = "支付宝";
                }

                if ($re_data['ways_source'] == 'weixin') {
                    $re_data['ways_source_desc'] = "微信支付";
                }

                if ($re_data['ways_source'] == 'jd') {
                    $re_data['ways_source_desc'] = "京东支付";
                }

                if ($re_data['ways_source'] == 'unionpay') {
                    $re_data['ways_source_desc'] = "银联";
                }
            } elseif ($tra_data_arr['pay_status'] == '2') {
                //正在支付
                $re_data['ways_source'] = $tra_data_arr['data']['ways_source']??"";
                $re_data['result_code'] = 'USERPAYING';
                $re_data['result_msg'] = '用户正在支付';
                $re_data['out_trade_no'] = $tra_data_arr['data']['out_trade_no'];
                if ($re_data['ways_source'] == 'alipay') {
                    $re_data['ways_source_desc'] = "支付宝";
                }

                if ($re_data['ways_source'] == 'weixin') {
                    $re_data['ways_source_desc'] = "微信支付";
                }

                if ($re_data['ways_source'] == 'jd') {
                    $re_data['ways_source_desc'] = "京东支付";
                }

                if ($re_data['ways_source'] == 'unionpay') {
                    $re_data['ways_source_desc'] = "银联";
                }
            } else {
                //其他错误
                $re_data['ways_source'] = $tra_data_arr['data']['ways_source']??"";
                $re_data['result_code'] = 'FALL';
                $re_data['result_msg'] = $tra_data_arr['message'];
                if ($re_data['ways_source'] == 'alipay') {
                    $re_data['ways_source_desc'] = "支付宝";
                }

                if ($re_data['ways_source'] == 'weixin') {
                    $re_data['ways_source_desc'] = "微信支付";
                }

                if ($re_data['ways_source'] == 'jd') {
                    $re_data['ways_source_desc'] = "京东支付";
                }

                if ($re_data['ways_source'] == 'unionpay') {
                    $re_data['ways_source_desc'] = "银联";
                }
                //处理支付失败订单

                if ($tra_data_arr['pay_status'] == '3' || $tra_data_arr['pay_status'] == 3) {
                    if (!empty($tra_data_arr['data']['out_trade_no'])) {
                        $payservice=new PayService();
                        $payservice->closeOrder($tra_data_arr['data']['out_trade_no'],(int)$tra_data_arr['pay_status']);
                    }
                }
                //处理支付失败订单
            }
            return $this->return_data($re_data);
        } catch (\Exception $exception) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine()
            ];
            return $this->return_data($err);
        }
    }

    //查询原订单
    public function order_query_v2(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);
            // //验证签名
            $check = $this->check_md5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }

            $other_no = isset($data['other_no']) ? $data['other_no'] : '';
            $out_trade_no = isset($data['out_trade_no']) ? $data['out_trade_no'] : "";
            $device_id = $data['device_id'];
            $device_type = $data['device_type'];

            $store_id = isset($data['store_id']) ? $data['store_id'] : "";
            $merchant_id = isset($data['merchant_id']) ? $data['merchant_id'] : "";

            //有门店ID
            if ($store_id) {
                $merchant_name = '';
                $config_id = '';
            } else {
                //银豹
                if ($device_type == "pospal") {
                    $merchant_id = '0';
                    $merchant_name = '0';
                    $store_id = $device_id;
                    $config_id = '';
                } else {
                    $Device = Device::where('device_type', $device_type)
                        ->where('device_no', $device_id)
                        ->first();
                    if (!$Device) {
                        $err = [
                            'return_code' => 'FALL',
                            'return_msg' => '设备未绑定'
                        ];
                        return $this->return_data($err);
                    }

                    $merchant_id = $Device->merchant_id;
                    $merchant_name = $Device->merchant_name;
                    $store_id = $Device->store_id;
                    $store_name = $Device->store_name;
                    $config_id = $Device->config_id;
                }
            }

            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
                'other_no' => $other_no,
                'store_id' => $store_id
            ];

            $data = [
                'out_trade_no' => $out_trade_no,
                'other_no' => $other_no,
                'store_id' => $store_id,
                'ways_type' => '',
                'config_id' => $config_id
            ];

            $order_obj = new OrderController();
            $return = $order_obj->order_foreach_public($data);
            $tra_data_arr = json_decode($return, true);
            if(empty($re_data['ways_source'])){
                $re_data['ways_source'] = $tra_data_arr['data']['ways_source'];
            }
            if ($tra_data_arr['status'] != 1) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $tra_data_arr['message']
                ];
                return $this->return_data($err);
            }

            //用户支付成功
            if ($tra_data_arr['pay_status'] == '1') {
                //微信，支付宝支付凭证
                $re_data['result_code'] = 'SUCCESS';
                $re_data['result_msg'] = '支付成功';
                $re_data['out_trade_no'] = $tra_data_arr['data']['out_trade_no'];
                $re_data['out_transaction_id'] = $tra_data_arr['data']['out_trade_no'];
                $re_data['pay_time'] = date('YmdHis', strtotime($tra_data_arr['data']['pay_time']));
                $re_data['ways_source'] = $tra_data_arr['data']['ways_source'];
                $re_data['pay_amount'] = isset($tra_data_arr['data']['pay_amount']) ? $tra_data_arr['data']['pay_amount'] : "";
                $re_data['total_amount'] = isset($tra_data_arr['data']['total_amount']) ? $tra_data_arr['data']['total_amount'] : "";
                $re_data['other_no'] = isset($tra_data_arr['data']['other_no']) ? $tra_data_arr['data']['other_no'] : "";
                $re_data['trade_no'] = $tra_data_arr['data']['trade_no'];



                //
                if ($re_data['ways_source'] == 'alipay') {
                    $re_data['ways_source_desc'] = "支付宝";
                }

                if ($re_data['ways_source'] == 'weixin') {
                    $re_data['ways_source_desc'] = "微信支付";
                }

                if ($re_data['ways_source'] == 'jd') {
                    $re_data['ways_source_desc'] = "京东支付";
                }

                if ($re_data['ways_source'] == 'unionpay') {
                    $re_data['ways_source_desc'] = "银联";
                }
            } elseif ($tra_data_arr['pay_status'] == '2') {
                //正在支付
                $re_data['ways_source'] = $tra_data_arr['data']['ways_source'];
                $re_data['result_code'] = 'USERPAYING';
                $re_data['result_msg'] = '用户正在支付';
                $re_data['out_trade_no'] = $tra_data_arr['data']['out_trade_no'];
                if ($re_data['ways_source'] == 'alipay') {
                    $re_data['ways_source_desc'] = "支付宝";
                }

                if ($re_data['ways_source'] == 'weixin') {
                    $re_data['ways_source_desc'] = "微信支付";
                }

                if ($re_data['ways_source'] == 'jd') {
                    $re_data['ways_source_desc'] = "京东支付";
                }

                if ($re_data['ways_source'] == 'unionpay') {
                    $re_data['ways_source_desc'] = "银联";
                }
            } else {
                //其他错误
                $re_data['ways_source'] = $tra_data_arr['data']['ways_source'];
                $re_data['result_code'] = 'SUCCESS';
                $re_data['result_msg'] = '支付成功';
                $re_data['out_trade_no'] = $tra_data_arr['data']['out_trade_no'];
                $re_data['out_transaction_id'] = $tra_data_arr['data']['out_trade_no'];
                $re_data['pay_time'] = date('YmdHis', time());
                $re_data['pay_amount'] = isset($tra_data_arr['data']['pay_amount']) ? $tra_data_arr['data']['pay_amount'] : "";
                $re_data['total_amount'] = isset($tra_data_arr['data']['total_amount']) ? $tra_data_arr['data']['total_amount'] : "";
                $re_data['trade_no'] = $tra_data_arr['data']['out_trade_no'];
                if ($re_data['ways_source'] == 'alipay') {
                    $re_data['ways_source_desc'] = "支付宝";
                }

                if ($re_data['ways_source'] == 'weixin') {
                    $re_data['ways_source_desc'] = "微信支付";
                }

                if ($re_data['ways_source'] == 'jd') {
                    $re_data['ways_source_desc'] = "京东支付";
                }

                if ($re_data['ways_source'] == 'unionpay') {
                    $re_data['ways_source_desc'] = "银联";
                }
            }
            return $this->return_data($re_data);
        } catch (\Exception $exception) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine()
            ];
            return $this->return_data($err);
        }
    }


    //退款接口
    public function refund(Request $request)
    {
        try {
            $data = $request->getContent();
            $data = json_decode($data, true);
            file_put_contents('refund.log',var_export($data,true)."\r\n",FILE_APPEND);

            //验证签名
            // $check = $this->check_md5($data);
            // if ($check['return_code'] == 'FALL') {
            //     return $this->return_data($check);
            // }

            $device_id = isset($data['device_id']) ? $data['device_id'] : "";
            $device_type = isset($data['device_type']) ? $data['device_type'] : "";
            $out_trade_no = isset($data['out_trade_no']) ? $data['out_trade_no'] : "";
            $refund_amount = isset($data['refund_amount']) ? $data['refund_amount'] : "";
            $refund_no = isset($data['refund_no'])?$data['refund_no'] : $out_trade_no . '123';

            $store_id = isset($data['store_id']) ? $data['store_id'] : "";
            $merchant_id = isset($data['merchant_id']) ? $data['merchant_id'] : "";

            //有门店ID
            if ($store_id) {
                $merchant_name = '';
                $config_id = '';
            } else {
                //银豹
                if ($device_type == "pospal") {
                    $merchant_id = '0';
                    $merchant_name = '0';
                    $store_id = $device_id;
                    $config_id = '';
                } else {
                    $Device = Device::where('device_type', $device_type)
                        ->where('device_no', $device_id)
                        ->first();
                    if (!$Device) {
                        $err = [
                            'return_code' => 'FALL',
                            'return_msg' => '设备未绑定'
                        ];
                        return $this->return_data($err);
                    }

                    $merchant_id = $Device->merchant_id;
                    $merchant_name = $Device->merchant_name;
                    $store_id = $Device->store_id;
                    $config_id = $Device->config_id;
                }
            }

            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
                'result_code' => '',
                'result_msg' => '',
                'store_id' => $store_id,
                'out_trade_no' => $out_trade_no,
                'refund_amount' => $refund_amount
            ];

            //请求参数
            $data = [
                'merchant_id' => $merchant_id,
                'out_trade_no' => $out_trade_no,
                'refund_amount' => $refund_amount,
                'refund_no' => $refund_no,
                'sxf_uuid' => isset($data['sxf_uuid']) ? $data['sxf_uuid'] : ""
            ];
            $pay_obj = new OrderController();
            $scan_pay_public = $pay_obj->refund_public($data);
            $tra_data_arr = json_decode($scan_pay_public, true);
             file_put_contents('refund.log',var_export($tra_data_arr,true)."\r\n",FILE_APPEND);

            if ($tra_data_arr['status'] != 1) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $tra_data_arr['message']
                ];
                return $this->return_data($err);
            }

            $re_data['other_no'] = $tra_data_arr['data']['other_no'];
            $re_data['refund_no'] = isset($tra_data_arr['data']['refund_no']) ? $tra_data_arr['data']['refund_no'] : $refund_no;
            $re_data['result_code'] = 'SUCCESS';
            $re_data['result_msg'] = '退款成功';

            $res_out_trade_no = isset($tra_data_arr['data']['out_trade_no']) ? $tra_data_arr['data']['out_trade_no'] : '';
            if ($res_out_trade_no) {
                $order_obj = Order::where('out_trade_no', $res_out_trade_no)->first();
                if ($order_obj) {
                    $re_data['ways_source'] = $order_obj->ways_source ? $order_obj->ways_source : '';

                    if ($re_data['ways_source'] == 'alipay') {
                        $re_data['ways_source_desc'] = "支付宝";
                    }

                    if ($re_data['ways_source'] == 'weixin') {
                        $re_data['ways_source_desc'] = "微信支付";
                    }

                    if ($re_data['ways_source'] == 'jd') {
                        $re_data['ways_source_desc'] = "京东支付";
                    }

                    if ($re_data['ways_source'] == 'unionpay') {
                        $re_data['ways_source_desc'] = "银联";
                    }
                }
            }
            return $this->return_data($re_data);
        } catch (\Exception $exception) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine()
            ];
            return $this->return_data($err);
        }
    }


    //退款查询接口
    public function refund_query(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);

            //验证签名
            $check = $this->check_md5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }

            $device_id = isset($data['device_id']) ? $data['device_id'] : "";
            $device_type = isset($data['device_type']) ? $data['device_type'] : "";
            $out_trade_no = isset($data['out_trade_no']) ? $data['out_trade_no'] : "";
            $store_id = isset($data['store_id']) ? $data['store_id'] : "";
            $refund_no = isset($data['refund_no']) ? $data['refund_no'] : "";
            $Order =DB::table('orders')->where('store_id', $store_id)->where('out_trade_no', $refund_no)->first();
            if(empty($Order)){
                $Order =DB::table('orders')->where('store_id', $store_id)->where('other_no', $refund_no)->first();
            }
            if(empty($Order->out_trade_no)){
                $RefundOrder = RefundOrder::query()
                    ->select('refund_amount','out_trade_no')
                    ->where('store_id', $store_id)
                    ->where(function ($query) use($refund_no){
                        $query->where('refund_no', $refund_no)
                            ->orWhere('other_refund_no', $refund_no);
                    })
                ->first();
            }else{
                $RefundOrder = RefundOrder::where('store_id', $store_id)
                ->where('out_trade_no', $Order->out_trade_no)
                ->select('refund_amount','out_trade_no')
                ->first();
            }
            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
                'result_code' => '',
                'result_msg' => '',
                'store_id' => $store_id,
                'out_trade_no' => $out_trade_no,
                'refund_amount' =>empty($RefundOrder)?0: $RefundOrder->refund_amount
            ];
            $re_data['result_code'] = 'SUCCESS';
            $re_data['result_msg'] = '退款成功';
            if (empty($RefundOrder)) {
                $refundService=new RefundService();
                $doing = RefundOrderDoing::query()->where("refund_no", $refund_no)->first();
                if (empty($doing)) {
                    throw new BizException("退款中的订单不存在");
                }
                $re_data["refund_amount"]=$doing->refund_amount;
                if($refundService->isRefundQuery($doing->company)){
                   $resultData=$refundService->refundQuery($doing,[
                        "refund_no"=>$refund_no,
                    ]);
                    if($resultData["status"]==-1){
                        $err = [
                            'return_code' => 'FALL',
                            'return_msg' => '退款请求失败'
                        ];
                        return $this->return_data($err);
                    }

                    if($resultData["status"]==1 && $resultData["data"]["refund_status"]==0){
                        $err = [
                            'return_code' => 'USERPAYING',
                            'return_msg' => '退款中'
                        ];
                        return $this->return_data($err);
                    }
                    if($resultData["status"]==1 && $resultData["data"]["refund_status"]==-1){
                        $err = [
                            'return_code' => 'FALL',
                            'return_msg' => '退款失败'
                        ];
                        return $this->return_data($err);
                    }
                }else{
                    $err = [
                        'return_code' => 'FALL',
                        'return_msg' => '退款单号不存在'
                    ];
                    return $this->return_data($err);
                }
            }
            if(empty($out_trade_no)){
                $out_trade_no=empty($RefundOrder->out_trade_no)?$doing->out_trade_no:$RefundOrder->out_trade_no;
            }


            if ($out_trade_no) {
                $order_obj = Order::where('out_trade_no', $out_trade_no)->first();
                if ($order_obj) {
                    $re_data['ways_source'] = $order_obj->ways_source ? $order_obj->ways_source : '';

                    if ($re_data['ways_source'] == 'alipay') {
                        $re_data['ways_source_desc'] = "支付宝";
                    }

                    if ($re_data['ways_source'] == 'weixin') {
                        $re_data['ways_source_desc'] = "微信支付";
                    }

                    if ($re_data['ways_source'] == 'jd') {
                        $re_data['ways_source_desc'] = "京东支付";
                    }

                    if ($re_data['ways_source'] == 'unionpay') {
                        $re_data['ways_source_desc'] = "银联";
                    }
                }
            }
            return $this->return_data($re_data);
        } catch (\Exception $exception) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine()
            ];
            return $this->return_data($err);
        }
    }


    //对账查询
    public function order(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);

            //验证签名
            $check = $this->check_md5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }

            $time_start = $data['time_start'];
            $time_end = $data['time_end'];
            $device_id = $data['device_id'];
            $device_type = $data['device_type'];

            $check_data = [
                'time_start' => '开始时间',
                'time_end' => '结束时间'
            ];
            $check = $this->check_required($data, $check_data);
            if ($check) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $check
                ];
                return $this->return_data($err);
            }

            $store_id = isset($data['store_id']) ? $data['store_id'] : "";
            $merchant_id = isset($data['merchant_id']) ? $data['merchant_id'] : "";

            //有门店ID
            if ($store_id) {
                $merchant_name = '';
                $config_id = '';
            } else {
                $Device = Device::where('device_type', $device_type)
                    ->where('device_no', $device_id)
                    ->first();
                if (!$Device) {
                    $err = [
                        'return_code' => 'FALL',
                        'return_msg' => '设备未绑定'
                    ];
		    
                    return $this->return_data($err);
                }

                $merchant_id = $Device->merchant_id;
                $merchant_name = $Device->merchant_name;
                $store_id = $Device->store_id;
                $store_name = $Device->store_name;
                $config_id = $Device->config_id;
            }

            //公共返回参数
            $request_data = [
                'store_id' => $store_id,
                'merchant_id' => $merchant_id,
                'time_start' => $time_start,
                'time_end' => $time_end
            ];
            $data = $this->order_count_public($request_data);
            if ($data['status'] != 1) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $data['message']
                ];
		
                return $this->return_data($err);
            }

            $re_data = $data['data'];
            $re_data['return_code'] = 'SUCCESS';
            $re_data['return_msg'] = '返回成功';

            return $this->return_data($re_data);
        } catch (\Exception $exception) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine()
            ];
            return $this->return_data($err);
        }
    }


    //对账统计-比较全
    public function order_count_public($data)
    {
        try {
            $store_id = $data['store_id'];
            $merchant_id = $data['merchant_id'];
            $time_start = $data['time_start'];
            $time_end = $data['time_end'];

            $where = [];
            $whereIn = [];
            $store_ids = [];

            //条件查询
            if ($store_id) {
                $where[] = ['store_id', '=', $store_id];
                $store_ids = [
                    [
                        'store_id' => $store_id
                    ]
                ];
            } else {
                $MerchantStore = MerchantStore::where('merchant_id', $merchant_id)
                    ->select('store_id')
                    ->get();
                if (!$MerchantStore->isEmpty()) {
                    $store_ids = $MerchantStore->toArray();
                }
            }

            //是否传收银员ID
            if ($merchant_id) {
                $where[] = ['merchant_id', '=', $merchant_id];
            }

            if ($time_start) {
                $time_start = date('Y-m-d H:i:s', strtotime($time_start));
                $where[] = ['created_at', '>=', $time_start];
            }

            if ($time_end) {
                $time_end = date('Y-m-d H:i:s', strtotime($time_end));
                $where[] = ['created_at', '<=', $time_end];
            }

            //跨天操作
            $time_start_db = date('Ymd', strtotime($time_start));
            $time_end_db = date('Ymd', strtotime($time_end));;
            $is_ct_time = 0;
            if ($time_start_db != $time_end_db) {
                $is_ct_time = 1;
            }

            //区间
            $e_order = '0.00';

            $day = date('Ymd', strtotime($time_end));
            $table = 'orders_' . $day;

            if (env('DB_D1_HOST')) {
                //有没有跨天
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                        $obj = DB::connection("mysql_d1")->table('order_items');
                    } else {
                        $obj = DB::connection("mysql_d1")->table('orders');
                    }
                } else {
                    if (Schema::hasTable($table)) {
                        $obj = DB::connection("mysql_d1")->table($table);
                    } else {
                        if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                            $obj = DB::connection("mysql_d1")->table('order_items');
                        } else {
                            $obj = DB::connection("mysql_d1")->table('orders');
                        }
                    }
                }
            } else {
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                        $obj = DB::table('order_items');
                    } else {
                        $obj = DB::table('orders');
                    }
                } else {
                    if (Schema::hasTable($table)) {
                        $obj = DB::table($table);
                    } else {
                        if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                            $obj = DB::table('order_items');
                        } else {
                            $obj = DB::table('orders');
                        }
                    }
                }
            }

            if (env('DB_D1_HOST')) {
                //有没有跨天
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                        $obj1 = DB::connection("mysql_d1")->table('order_items');
                    } else {
                        $obj1 = DB::connection("mysql_d1")->table('orders');
                    }
                } else {
                    if (Schema::hasTable($table)) {
                        $obj1 = DB::connection("mysql_d1")->table($table);
                    } else {
                        if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                            $obj1 = DB::connection("mysql_d1")->table('order_items');
                        } else {
                            $obj1 = DB::connection("mysql_d1")->table('orders');
                        }
                    }
                }
            } else {
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                        $obj1 = DB::table('order_items');
                    } else {
                        $obj1 = DB::table('orders');
                    }
                } else {
                    if (Schema::hasTable($table)) {
                        $obj1 = DB::table($table);
                    } else {
                        if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                            $obj1 = DB::table('order_items');
                        } else {
                            $obj1 = DB::table('orders');
                        }
                    }
                }
            }

            if (env('DB_D1_HOST')) {
                //有没有跨天
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                        $obj2 = DB::connection("mysql_d1")->table('order_items');
                    } else {
                        $obj2 = DB::connection("mysql_d1")->table('orders');
                    }
                } else {
                    if (Schema::hasTable($table)) {
                        $obj2 = DB::connection("mysql_d1")->table($table);
                    } else {
                        if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                            $obj2 = DB::connection("mysql_d1")->table('order_items');
                        } else {
                            $obj2 = DB::connection("mysql_d1")->table('orders');
                        }
                    }
                }
            } else {
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                        $obj2 = DB::table('order_items');
                    } else {
                        $obj2 = DB::table('orders');
                    }
                } else {
                    if (Schema::hasTable($table)) {
                        $obj2 = DB::table($table);
                    } else {
                        if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                            $obj2 = DB::table('order_items');
                        } else {
                            $obj2 = DB::table('orders');
                        }
                    }
                }
            }

            if (env('DB_D1_HOST')) {
                //有没有跨天
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                        $obj3 = DB::connection("mysql_d1")->table('order_items');
                    } else {
                        $obj3 = DB::connection("mysql_d1")->table('orders');
                    }
                } else {
                    if (Schema::hasTable($table)) {
                        $obj3 = DB::connection("mysql_d1")->table($table);
                    } else {
                        if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                            $obj3 = DB::connection("mysql_d1")->table('order_items');
                        } else {
                            $obj3 = DB::connection("mysql_d1")->table('orders');
                        }
                    }
                }
            } else {
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                        $obj3 = DB::table('order_items');
                    } else {
                        $obj3 = DB::table('orders');
                    }
                } else {
                    if (Schema::hasTable($table)) {
                        $obj3 = DB::table($table);
                    } else {
                        if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                            $obj3 = DB::table('order_items');
                        } else {
                            $obj3 = DB::table('orders');
                        }
                    }
                }
            }

            if (env('DB_D1_HOST')) {
                //有没有跨天
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                        $obj4 = DB::connection("mysql_d1")->table('order_items');
                    } else {
                        $obj4 = DB::connection("mysql_d1")->table('orders');
                    }
                } else {
                    if (Schema::hasTable($table)) {
                        $obj4 = DB::connection("mysql_d1")->table($table);
                    } else {
                        if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                            $obj4 = DB::connection("mysql_d1")->table('order_items');
                        } else {
                            $obj4 = DB::connection("mysql_d1")->table('orders');
                        }
                    }
                }
            } else {
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                        $obj4 = DB::table('order_items');
                    } else {
                        $obj4 = DB::table('orders');
                    }
                } else {
                    if (Schema::hasTable($table)) {
                        $obj4 = DB::table($table);
                    } else {
                        if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                            $obj4 = DB::table('order_items');
                        } else {
                            $obj4 = DB::table('orders');
                        }
                    }
                }
            }

            if (env('DB_D1_HOST')) {
                //有没有跨天
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                        $obj5 = DB::connection("mysql_d1")->table('order_items');
                    } else {
                        $obj5 = DB::connection("mysql_d1")->table('orders');
                    }
                } else {
                    if (Schema::hasTable($table)) {
                        $obj5 = DB::connection("mysql_d1")->table($table);
                    } else {
                        if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                            $obj5 = DB::connection("mysql_d1")->table('order_items');
                        } else {
                            $obj5 = DB::connection("mysql_d1")->table('orders');
                        }
                    }
                }
            } else {
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                        $obj5 = DB::table('order_items');
                    } else {
                        $obj5 = DB::table('orders');
                    }
                } else {
                    if (Schema::hasTable($table)) {
                        $obj5 = DB::table($table);
                    } else {
                        if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                            $obj5 = DB::table('order_items');
                        } else {
                            $obj5 = DB::table('orders');
                        }
                    }
                }
            }

            if ($merchant_id) {
                $order_data =$obj->where($where)
                    ->whereIn('pay_status', [1, 6])//成功+退款
                    ->where('merchant_id', $merchant_id)
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');

                $refund_obj = RefundOrder::where('merchant_id', $merchant_id)
                    ->where($where)
                    ->select('refund_amount');

                //支付宝
                $alipay_order_data = $obj1->where($where)
                    ->whereIn('pay_status', [1, 6])//成功+退款
                    ->where('ways_source', 'alipay')
                    ->where('merchant_id', $merchant_id)
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');

                $alipay_refund_obj = RefundOrder::where('merchant_id', $merchant_id)
                    ->where('ways_source', 'alipay')
                    ->where($where)
                    ->select('refund_amount');


                //微信
                $weixin_order_data = $obj2->where($where)
                    ->whereIn('pay_status', [1, 6])//成功+退款
                    ->where('ways_source', 'weixin')
                    ->where('merchant_id', $merchant_id)
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');

                $weixin_refund_obj = RefundOrder::where('merchant_id', $merchant_id)
                    ->where('ways_source', 'weixin')
                    ->where($where)
                    ->select('refund_amount');

                //京东
                $jd_order_data = $obj3->where($where)
                    ->whereIn('pay_status', [1, 6])//成功+退款
                    ->where('ways_source', 'jd')
                    ->where('merchant_id', $merchant_id)
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');

                $jd_refund_obj = RefundOrder::where('merchant_id', $merchant_id)
                    ->where('ways_source', 'jd')
                    ->where($where)
                    ->select('refund_amount');

                //银联刷卡
                $un_order_data = $obj4->where($where)
                    ->whereIn('pay_status', [1, 6])//成功+退款
                    ->whereIn('ways_type', [6005, 8005])//新大陆+京东刷卡
                    ->where('ways_source', 'unionpay')
                    ->where('merchant_id', $merchant_id)
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');

                $un_refund_obj = RefundOrder::where('merchant_id', $merchant_id)
                    ->whereIn('type', [6005, 8005])//新大陆+京东刷卡
                    ->where('ways_source', 'unionpay')
                    ->where($where)
                    ->select('refund_amount');

                //银联扫码
                $unqr_order_data = $obj5->where($where)
                    ->whereIn('pay_status', [1, 6])//成功+退款
                    ->whereNotIn('ways_type', [6005, 8005])//新大陆+京东刷卡
                    ->where('ways_source', 'unionpay')
                    ->where('merchant_id', $merchant_id)
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');

                $unqr_refund_obj = RefundOrder::where('merchant_id', $merchant_id)
                    ->whereNotIn('type', [6005, 8005])//新大陆+京东刷卡
                    ->where('ways_source', 'unionpay')
                    ->where($where)
                    ->select('refund_amount');
            } else {
                $order_data =  $obj->whereIn('store_id', $store_ids)
                    ->where($where)
                    ->whereIn('pay_status', [1, 6])//成功+退款
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');

                $refund_obj = RefundOrder::whereIn('store_id', $store_ids)
                    ->where($where)
                    ->select('refund_amount');

                //支付宝
                $alipay_order_data =  $obj1->whereIn('store_id', $store_ids)
                    ->where($where)
                    ->whereIn('pay_status', [1, 6])//成功+退款
                    ->where('ways_source', 'alipay')
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');

                $alipay_refund_obj = RefundOrder::whereIn('store_id', $store_ids)
                    ->where($where)
                    ->where('ways_source', 'alipay')
                    ->select('refund_amount');

                //微信
                $weixin_order_data = $obj2->whereIn('store_id', $store_ids)
                    ->where($where)
                    ->whereIn('pay_status', [1, 6])//成功+退款
                    ->where('ways_source', 'weixin')
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');

                $weixin_refund_obj = RefundOrder::whereIn('store_id', $store_ids)
                    ->where($where)
                    ->where('ways_source', 'weixin')
                    ->select('refund_amount');

                //京东
                $jd_order_data =  $obj3->whereIn('store_id', $store_ids)
                    ->where($where)
                    ->whereIn('pay_status', [1, 6])//成功+退款
                    ->where('ways_source', 'jd')
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');

                $jd_refund_obj = RefundOrder::whereIn('store_id', $store_ids)
                    ->where($where)
                    ->where('ways_source', 'jd')
                    ->select('refund_amount');

                //银联刷卡
                $un_order_data = $obj4->whereIn('store_id', $store_ids)
                    ->where($where)
                    ->whereIn('pay_status', [1, 6])//成功+退款
                    ->whereIn('ways_type', [6005, 8005])//新大陆+京东刷卡
                    ->where('ways_source', 'unionpay')
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');

                $un_refund_obj = RefundOrder::whereIn('store_id', $store_ids)
                    ->where($where)
                    ->where('ways_source', 'unionpay')
                    ->whereIn('type', [6005, 8005])//新大陆+京东刷卡
                    ->select('refund_amount');

                //银联二维码
                $unqr_order_data = $obj5->whereIn('store_id', $store_ids)
                    ->where($where)
                    ->whereIn('pay_status', [1, 6])//成功+退款
                    ->whereNotIn('ways_type', [6005, 8005])//去除新大陆+京东刷卡
                    ->where('ways_source', 'unionpay')
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');

                $unqr_refund_obj = RefundOrder::whereIn('store_id', $store_ids)
                    ->where($where)
                    ->where('ways_source', 'unionpay')
                    ->whereNotIn('type', [6005, 8005])//去除新大陆+京东刷卡
                    ->select('refund_amount');
            }

            //总的
            $total_amount = $order_data->sum('total_amount');//交易金额
            $refund_amount = $refund_obj->sum('refund_amount');//退款金额
            $fee_amount = $order_data->sum('fee_amount');//结算服务费/手续费
            $mdiscount_amount = '0';//$order_data->sum('mdiscount_amount');//商家优惠金额
            $get_amount = $total_amount - $refund_amount - $mdiscount_amount;//商家实收，交易金额-退款金额
            $receipt_amount = $get_amount - $fee_amount;//实际净额，实收-手续费
            $e_order = '' . $e_order . '';
            $total_count = '' . count($order_data->get()) . '';
            $refund_count = count($refund_obj->get());

            //支付宝
            $alipay_total_amount = $alipay_order_data->sum('total_amount');//交易金额
            $alipay_refund_amount = $alipay_refund_obj->sum('refund_amount');//退款金额
            $alipay_fee_amount = $alipay_order_data->sum('fee_amount');//结算服务费/手续费
            $alipay_mdiscount_amount = '0';// $alipay_order_data->sum('mdiscount_amount');//商家优惠金额
            $alipay_get_amount = $alipay_total_amount - $alipay_refund_amount - $alipay_mdiscount_amount;//商家实收，交易金额-退款金额
            $alipay_receipt_amount = $alipay_get_amount - $alipay_fee_amount;//实际净额，实收-手续费
            $alipay_total_count = '' . count($alipay_order_data->get()) . '';
            $alipay_refund_count = count($alipay_refund_obj->get());

            //微信
            $weixin_total_amount = $weixin_order_data->sum('total_amount');//交易金额
            $weixin_refund_amount = $weixin_refund_obj->sum('refund_amount');//退款金额
            $weixin_fee_amount = $weixin_order_data->sum('fee_amount');//结算服务费/手续费
            $weixin_mdiscount_amount = '0';// $weixin_order_data->sum('mdiscount_amount');//商家优惠金额
            $weixin_get_amount = $weixin_total_amount - $weixin_refund_amount - $weixin_mdiscount_amount;//商家实收，交易金额-退款金额
            $weixin_receipt_amount = $weixin_get_amount - $weixin_fee_amount;//实际净额，实收-手续费
            $weixin_total_count = '' . count($weixin_order_data->get()) . '';
            $weixin_refund_count = count($weixin_refund_obj->get());

            //京东
            $jd_total_amount = $jd_order_data->sum('total_amount');//交易金额
            $jd_refund_amount = $jd_refund_obj->sum('refund_amount');//退款金额
            $jd_fee_amount = $jd_order_data->sum('fee_amount');//结算服务费/手续费
            $jd_mdiscount_amount = '0';// $jd_order_data->sum('mdiscount_amount');//商家优惠金额
            $jd_get_amount = $jd_total_amount - $jd_refund_amount - $jd_mdiscount_amount;//商家实收，交易金额-退款金额
            $jd_receipt_amount = $jd_get_amount - $jd_fee_amount;//实际净额，实收-手续费
            $jd_total_count = '' . count($jd_order_data->get()) . '';
            $jd_refund_count = count($jd_refund_obj->get());

            //银联刷卡
            $un_total_amount = $un_order_data->sum('total_amount');//交易金额
            $un_refund_amount = $un_refund_obj->sum('refund_amount');//退款金额
            $un_fee_amount = $un_order_data->sum('fee_amount');//结算服务费/手续费
            $un_mdiscount_amount = '0';//$un_order_data->sum('mdiscount_amount');//商家优惠金额
            $un_get_amount = $un_total_amount - $un_refund_amount - $un_mdiscount_amount;//商家实收，交易金额-退款金额
            $un_receipt_amount = $un_get_amount - $un_fee_amount;//实际净额，实收-手续费
            $un_total_count = '' . count($un_order_data->get()) . '';
            $un_refund_count = count($un_refund_obj->get());

            //银联扫码
            $unqr_total_amount = $unqr_order_data->sum('total_amount');//交易金额
            $unqr_refund_amount = $unqr_refund_obj->sum('refund_amount');//退款金额
            $unqr_fee_amount = $unqr_order_data->sum('fee_amount');//结算服务费/手续费
            $unqr_mdiscount_amount = '0';//$unqr_order_data->sum('mdiscount_amount');//商家优惠金额
            $unqr_get_amount = $unqr_total_amount - $unqr_refund_amount - $unqr_mdiscount_amount;//商家实收，交易金额-退款金额
            $unqr_receipt_amount = $unqr_get_amount - $unqr_fee_amount;//实际净额，实收-手续费
            $unqr_total_count = '' . count($unqr_order_data->get()) . '';
            $unqr_refund_count = count($unqr_refund_obj->get());

            $data = [
                'total_amount' => number_format($total_amount, 2, '.', ''),//交易金额
                'total_count' => '' . $total_count . '',//交易笔数
                'refund_count' => '' . $refund_count . '',//退款金额
                'get_amount' => number_format($get_amount, 2, '.', ''),//商家实收，交易金额-退款金额
                'refund_amount' => number_format($refund_amount, 2, '.', ''),//退款金额
                'receipt_amount' => number_format($receipt_amount, 2, '.', ''),//实际净额，实收-手续费
                'fee_amount' => number_format($fee_amount, 2, '.', ''),//结算服务费/手续费
                'mdiscount_amount' => number_format($mdiscount_amount, 2, '.', ''),

                'alipay_total_amount' => number_format($alipay_total_amount, 2, '.', ''),//交易金额
                'alipay_total_count' => '' . $alipay_total_count . '',//交易笔数
                'alipay_refund_count' => '' . $alipay_refund_count . '',//退款金额
                'alipay_get_amount' => number_format($alipay_get_amount, 2, '.', ''),//商家实收，交易金额-退款金额
                'alipay_refund_amount' => number_format($alipay_refund_amount, 2, '.', ''),//退款金额
                'alipay_receipt_amount' => number_format($alipay_receipt_amount, 2, '.', ''),//实际净额，实收-手续费
                'alipay_fee_amount' => number_format($alipay_fee_amount, 2, '.', ''),//结算服务费/手续费
                'alipay_mdiscount_amount' => number_format($alipay_mdiscount_amount, 2, '.', ''),

                'weixin_total_amount' => number_format($weixin_total_amount, 2, '.', ''),//交易金额
                'weixin_total_count' => '' . $weixin_total_count . '',//交易笔数
                'weixin_refund_count' => '' . $weixin_refund_count . '',//退款金额
                'weixin_get_amount' => number_format($weixin_get_amount, 2, '.', ''),//商家实收，交易金额-退款金额
                'weixin_refund_amount' => number_format($weixin_refund_amount, 2, '.', ''),//退款金额
                'weixin_receipt_amount' => number_format($weixin_receipt_amount, 2, '.', ''),//实际净额，实收-手续费
                'weixin_fee_amount' => number_format($weixin_fee_amount, 2, '.', ''),//结算服务费/手续费
                'weixin_mdiscount_amount' => number_format($weixin_mdiscount_amount, 2, '.', ''),

                'jd_total_amount' => number_format($jd_total_amount, 2, '.', ''),//交易金额
                'jd_total_count' => '' . $jd_total_count . '',//交易笔数
                'jd_refund_count' => '' . $jd_refund_count . '',//退款金额
                'jd_get_amount' => number_format($jd_get_amount, 2, '.', ''),//商家实收，交易金额-退款金额
                'jd_refund_amount' => number_format($jd_refund_amount, 2, '.', ''),//退款金额
                'jd_receipt_amount' => number_format($jd_receipt_amount, 2, '.', ''),//实际净额，实收-手续费
                'jd_fee_amount' => number_format($jd_fee_amount, 2, '.', ''),//结算服务费/手续费
                'jd_mdiscount_amount' => number_format($jd_mdiscount_amount, 2, '.', ''),

                'un_total_amount' => number_format($un_total_amount, 2, '.', ''),//交易金额
                'un_total_count' => '' . $un_total_count . '',//交易笔数
                'un_refund_count' => '' . $un_refund_count . '',//退款金额
                'un_get_amount' => number_format($un_get_amount, 2, '.', ''),//商家实收，交易金额-退款金额
                'un_refund_amount' => number_format($un_refund_amount, 2, '.', ''),//退款金额
                'un_receipt_amount' => number_format($un_receipt_amount, 2, '.', ''),//实际净额，实收-手续费
                'un_fee_amount' => number_format($un_fee_amount, 2, '.', ''),//结算服务费/手续费
                'un_mdiscount_amount' => number_format($un_mdiscount_amount, 2, '.', ''),

                'unqr_total_amount' => number_format($unqr_total_amount, 2, '.', ''),//交易金额
                'unqr_total_count' => '' . $unqr_total_count . '',//交易笔数
                'unqr_refund_count' => '' . $unqr_refund_count . '',//退款金额
                'unqr_get_amount' => number_format($unqr_get_amount, 2, '.', ''),//商家实收，交易金额-退款金额
                'unqr_refund_amount' => number_format($unqr_refund_amount, 2, '.', ''),//退款金额
                'unqr_receipt_amount' => number_format($unqr_receipt_amount, 2, '.', ''),//实际净额，实收-手续费
                'unqr_fee_amount' => number_format($unqr_fee_amount, 2, '.', ''),//结算服务费/手续费
                'unqr_mdiscount_amount' => number_format($unqr_mdiscount_amount, 2, '.', ''),

            ];

            return [
                'status' => 1,
                'message' => '数据返回成功',
                'data' => $data
            ];
        } catch (\Exception $exception) {
            return [
                'status' => 2,
                'message' => $exception->getMessage()
            ];
        }
    }


    public function order_list(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);

            //验证签名
            $check = $this->check_md5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }

            $device_id = $data['device_id'];
            $device_type = $data['device_type'];

            $store_id = isset($data['store_id']) ? $data['store_id'] : "";
            $merchant_id = isset($data['merchant_id']) ? $data['merchant_id'] : "";
            $time_start_s = date('Y-m-d 00:00:00', time());
            $time_start_e = date('Y-m-d 23:59:59', time());

            $time_start =$time_start_s;
            $time_end =$time_start_e;

            //有门店ID
            if ($store_id) {
                $merchant_name = '';
                $config_id = '';
            } else {
                $Device = Device::where('device_type', $device_type)
                    ->where('device_no', $device_id)
                    ->first();
                if (!$Device) {
                    $err = [
                        'return_code' => 'FALL',
                        'return_msg' => '设备未绑定'
                    ];
                    return $this->return_data($err);
                }

                $merchant_id = $Device->merchant_id;
                $merchant_name = $Device->merchant_name;
                $store_id = $Device->store_id;
                $store_name = $Device->store_name;
                $config_id = $Device->config_id;
            }

            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
                'store_id' => $store_id
            ];
            $where = [];
            if ($merchant_id) {
                $where[] = ['merchant_id', '=', $merchant_id];
            }

            if ($store_id) {
                $where[] = ['store_id', '=', $store_id];
            }

            //跨天操作
            $time_start_db = date('Ymd', strtotime($time_start));
            $time_end_db = date('Ymd', strtotime($time_end));;
            $is_ct_time = 0;
            if ($time_start_db != $time_end_db) {
                $is_ct_time = 1;
            }

            $day = date('Ymd', strtotime($time_end));
            $table = 'orders_' . $day;
            if (env('DB_D1_HOST')) {
                //有没有跨天
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                        $obj = DB::connection("mysql_d1")->table('order_items');
                    } else {
                        $obj = DB::connection("mysql_d1")->table('orders');
                    }
                } else {
                    if (Schema::hasTable($table)) {
                        $obj = DB::connection("mysql_d1")->table($table);
                    } else {
                        if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                            $obj = DB::connection("mysql_d1")->table('order_items');
                        } else {
                            $obj = DB::connection("mysql_d1")->table('orders');
                        }
                    }
                }
            } else {
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                        $obj = DB::table('order_items');
                    } else {
                        $obj = DB::table('orders');
                    }
                } else {
                    if (Schema::hasTable($table)) {
                        $obj = DB::table($table);
                    } else {
                        if (Schema::hasTable('order_items')&&$time_start>="2019-12-21 00:00:00") {
                            $obj = DB::table('order_items');
                        } else {
                            $obj = DB::table('orders');
                        }
                    }
                }
            }

            $re_data['data'] =$obj->where($where)
                ->where('pay_status', 1)
                ->select('total_amount', 'ways_source_desc', 'pay_time')
                ->orderBy('created_at', 'desc')
                ->take(5)
                ->get();

            return $this->return_data($re_data);
        } catch (\Exception $exception) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine()
            ];
            return $this->return_data($err);
        }
    }
    
    public function jiujiang_refund(Request $request)
    {
        try {
            $data = $request->getContent();
            $data = json_decode($data, true);
            $store_id = $data['store_id'];
            $refund_amount = $data['refund_amount'];
            $refund_no = $data['refund_no'];
            $store = Store::where('store_id', $store_id)
                ->select('config_id', 'merchant_id', 'pid')
                ->first();

            $store_pid = $store->pid;
            $config = new \App\Api\Controllers\Config\JiuJiangConfigController();
            $jiujiang_merchant = $config->jiujiang_merchant($store_id, $store_pid);
            if (!$jiujiang_merchant) {
                return json_encode([
                    'status' => '2',
                    'message' => '九江银行商户号不存在'
                ]);
            }

            $txnAmt = substr( strval($refund_amount * 100 + 1000000000000), 1, 15 ); // 交易金额（分，12 位，不足左补 0）

            $refund_data = [
                'requestBranchCode' => '0220200000033',
                'mchtNo' => $jiujiang_merchant->mchtNo, // 平台分配的商户号
                'termNo' => $jiujiang_merchant->termNo, // 平台分配的终端号
                'secMchtNo' => $jiujiang_merchant->mchtNo,

                'outOrderNo' => $refund_no,
                'orderName' => '正常退款', // 交易金额（分，12 位，不足左补 0）
                'orderTime' => date('His', time()),
                'orderDate' => date('md', time()),
                'txnAmt' => $txnAmt,
                'oriTxnDate'=>date('Ymd', time()),
                'mchtOrderNo'=> $data['out_trade_no'],
            ];

            $obj = new \App\Api\Controllers\JiuJiang\PayController();
            $return = $obj->refund($refund_data,$jiujiang_merchant->private_key); //-1系统错误；0-其他；1-处理成功；2-验签失败 
           
            if (isset($return['status'])) {
                if ($return['status'] == 1) {
                    $out_trade_no = $return['data']['origOrderNo'];
                    $order = Order::where('out_trade_no', $out_trade_no)->first();


                    $out_trade_no = $order->out_trade_no;
                    $total_amount = $order->total_amount; //交易总额

                    $rate = $order->rate; //订单但是费率
                    $new_refund_amount = $order->refund_amount + $refund_amount; //总退款
                    $new_fee_amount = ($total_amount - $new_refund_amount) * ($rate/100); //退款后的手续费


                    $insert_data = [
                        'status' => '6',
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];

                    (new \App\Api\Controllers\BaseController())->update_day_order($insert_data, $out_trade_no);

                    \App\Models\RefundOrder::create([
                        'ways_source' => $order->ways_source,
                        'type' => $order->ways_type,
                        'refund_amount' => $refund_amount, //退款金额
                        'refund_no' => $refund_no, //联动流水号
                        'store_id' => $store_id,
                        'merchant_id' => $order->merchant_id,
                        'out_trade_no' => $out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$refund_no, //平台退款单号
                    ]);
                    $data = [
                        'refund_amount' => $refund_amount,
                        'out_trade_no' => $out_trade_no,
                        'refund_no' => $return['data']['outOrderNo'], //联动流水号
                        'other_no' => $order->other_no
                    ];

                    //返佣去掉
                    \App\Models\UserWalletDetail::where('out_trade_no', $out_trade_no)->update([
                        'settlement' => '03',
                        'settlement_desc' => '退款订单',
                    ]);
                    \App\Models\MerchantWalletDetail::where('out_trade_no', $out_trade_no)->update([
                        'settlement' => '03',
                        'settlement_desc' => '退款订单',
                    ]);

                    //公共返回参数
                    $re_data = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => '返回成功',
                        'result_code' => '',
                        'result_msg' => '',
                        'store_id' => $store_id,
                        'out_trade_no' => $out_trade_no,
                        'refund_amount' => $refund_amount
                    ];

                    $re_data['other_no'] = $order->other_no;
                    $re_data['refund_no'] = $refund_no;
                    $re_data['result_code'] = 'SUCCESS';
                    $re_data['result_msg'] = '退款成功';

                    if ($order->ways_source == 'alipay') {
                        $re_data['ways_source_desc'] = "支付宝";
                    }

                    if ($order->ways_source == 'weixin') {
                        $re_data['ways_source_desc'] = "微信支付";
                    }

                    if ($order->ways_source == 'jd') {
                        $re_data['ways_source_desc'] = "京东支付";
                    }

                    if ($order->ways_source == 'unionpay') {
                        $re_data['ways_source_desc'] = "银联";
                    }
                    return $this->return_data($re_data);
                } else {
                    $err = [
                        'return_code' => 'FALL',
                        'return_msg' => '退款失败'
                    ];
                    return $this->return_data($err);
                }
            } else {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => '系统异常'
                ];
                return $this->return_data($err);
            }
        } catch (\Exception $exception) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine()
            ];
            return $this->return_data($err);
        }
    }

    //处理支付失败订单
    public function closeOrder ($outTradeNo)
    {
        try {
            $dayOrderTable = 'orders_'.substr(preg_replace("/[a-zA-Z_]/", "", $outTradeNo), 0, 8);
            if (DB::connection()->getSchemaBuilder()->hasTable($dayOrderTable)) {
                $update = ['pay_status' => 3, 'pay_status_desc' => '支付失败', 'status' => 3];
                DB::beginTransaction();
                $re  = DB::table($dayOrderTable)->where('out_trade_no', $outTradeNo)->update($update);
                $res = DB::table('orders')->where('out_trade_no', $outTradeNo)->update($update);

                if ($res && $re) {
                    DB::commit();
                } else {
                    error_log(date('Y-m-d H:i:s')." 【关闭订单失败1】： ".json_encode([$res, $re, $outTradeNo])."\n\n", 3, "/tmp/". 'close-order'.date('Ymd').".log");
                    DB::rollBack();
                }
            } else {
                error_log(date('Y-m-d H:i:s')." 【关闭订单失败2】： ".json_encode([$dayOrderTable,$outTradeNo])."\n\n", 3, "/tmp/". 'close-order'.date('Ymd').".log");
            }
        } catch (\Exception $exception) {
            error_log(date('Y-m-d H:i:s')." 【关闭订单失败3】： ".json_encode([$exception->getMessage(),$outTradeNo])."\n\n", 3, "/tmp/". 'close-order'.date('Ymd').".log");
        }
    }

}
